From 10f0846c225c6403b1737815fd94dff9c6ca0bba Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 25 Jun 2020 12:37:33 +0200 Subject: [PATCH 01/42] add "@elastic/elasticsearch" to dependencies --- package.json | 2 +- yarn.lock | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 3eaa1fb05e906..0f4154f836bb5 100644 --- a/package.json +++ b/package.json @@ -125,6 +125,7 @@ "@elastic/apm-rum": "^5.2.0", "@elastic/charts": "19.5.2", "@elastic/datemath": "5.0.3", + "@elastic/elasticsearch": "^7.7.1", "@elastic/ems-client": "7.9.3", "@elastic/eui": "24.1.0", "@elastic/filesaver": "1.1.2", @@ -293,7 +294,6 @@ "devDependencies": { "@babel/parser": "^7.10.2", "@babel/types": "^7.10.2", - "@elastic/elasticsearch": "^7.4.0", "@elastic/eslint-config-kibana": "0.15.0", "@elastic/eslint-plugin-eui": "0.0.2", "@elastic/github-checks-reporter": "0.0.20b3", diff --git a/yarn.lock b/yarn.lock index b600ccb75c9fa..68ec20358511c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2172,6 +2172,17 @@ once "^1.4.0" pump "^3.0.0" +"@elastic/elasticsearch@^7.7.1": + version "7.7.1" + resolved "https://registry.yarnpkg.com/@elastic/elasticsearch/-/elasticsearch-7.7.1.tgz#ad95145fcd779206d101560cb90cdeb3041d2984" + integrity sha512-OzCitXAMQ4pC6EwtPCO0KBygjDFcBMBrJ6pBguYuZxtMbRLOPjcS1Er31N0+J6mp2Q8pU0HGm1FAGfGe6FJReQ== + dependencies: + debug "^4.1.1" + decompress-response "^4.2.0" + ms "^2.1.1" + pump "^3.0.0" + secure-json-parse "^2.1.0" + "@elastic/ems-client@7.9.3": version "7.9.3" resolved "https://registry.yarnpkg.com/@elastic/ems-client/-/ems-client-7.9.3.tgz#71b79914f76e347f050ead8474ad65d761e94a8a" @@ -27733,6 +27744,11 @@ scss-tokenizer@^0.2.3: js-base64 "^2.1.8" source-map "^0.4.2" +secure-json-parse@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/secure-json-parse/-/secure-json-parse-2.1.0.tgz#ae76f5624256b5c497af887090a5d9e156c9fb20" + integrity sha512-GckO+MS/wT4UogDyoI/H/S1L0MCcKS1XX/vp48wfmU7Nw4woBmb8mIpu4zPBQjKlRT88/bt9xdoV4111jPpNJA== + seedrandom@^3.0.5: version "3.0.5" resolved "https://registry.yarnpkg.com/seedrandom/-/seedrandom-3.0.5.tgz#54edc85c95222525b0c7a6f6b3543d8e0b3aa0a7" From e923ce5e6b66ac3d0b9c2d698213ce457920bc19 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 25 Jun 2020 12:50:41 +0200 Subject: [PATCH 02/42] first POC of new client --- .../elasticsearch/client/client_config.ts | 145 ++++++++++++++++++ .../elasticsearch/client/client_facade.ts | 57 +++++++ .../elasticsearch/client/client_wrapper.ts | 51 ++++++ .../elasticsearch/client/cluster_client.ts | 71 +++++++++ .../elasticsearch/client/configure_client.ts | 31 ++++ src/core/server/elasticsearch/client/index.ts | 18 +++ .../client/scoped_cluster_client.ts | 43 ++++++ src/core/server/elasticsearch/client/types.ts | 39 +++++ 8 files changed, 455 insertions(+) create mode 100644 src/core/server/elasticsearch/client/client_config.ts create mode 100644 src/core/server/elasticsearch/client/client_facade.ts create mode 100644 src/core/server/elasticsearch/client/client_wrapper.ts create mode 100644 src/core/server/elasticsearch/client/cluster_client.ts create mode 100644 src/core/server/elasticsearch/client/configure_client.ts create mode 100644 src/core/server/elasticsearch/client/index.ts create mode 100644 src/core/server/elasticsearch/client/scoped_cluster_client.ts create mode 100644 src/core/server/elasticsearch/client/types.ts diff --git a/src/core/server/elasticsearch/client/client_config.ts b/src/core/server/elasticsearch/client/client_config.ts new file mode 100644 index 0000000000000..3b6a4d57c60d6 --- /dev/null +++ b/src/core/server/elasticsearch/client/client_config.ts @@ -0,0 +1,145 @@ +/* + * 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 { ConnectionOptions as TlsConnectionOptions } from 'tls'; +import { URL } from 'url'; +import { Duration } from 'moment'; +import { ClientOptions, NodeOptions } from '@elastic/elasticsearch'; +import { ElasticsearchConfig } from '../elasticsearch_config'; + +/** + * @privateRemarks Config that consumers can pass to the Elasticsearch JS client is complex and includes + * not only entries from standard `elasticsearch.*` yaml config, but also some Elasticsearch JS + * client specific options like `keepAlive` or `plugins` (that eventually will be deprecated). + * + * @public + */ +export type ElasticsearchClientConfig = Pick< + ElasticsearchConfig, + | 'customHeaders' + | 'logQueries' + | 'sniffOnStart' + | 'sniffOnConnectionFault' + | 'requestHeadersWhitelist' + | 'sniffInterval' + | 'hosts' + | 'username' + | 'password' +> & { + pingTimeout?: ElasticsearchConfig['pingTimeout'] | ClientOptions['pingTimeout']; + requestTimeout?: ElasticsearchConfig['requestTimeout'] | ClientOptions['requestTimeout']; + ssl?: Partial; +}; + +export function parseClientOptions( + config: ElasticsearchClientConfig, + scoped: boolean +): ClientOptions { + const clientOptions: ClientOptions = { + sniffOnStart: config.sniffOnStart, + sniffOnConnectionFault: config.sniffOnConnectionFault, + headers: config.customHeaders, + }; + + if (config.pingTimeout != null) { + clientOptions.pingTimeout = getDurationAsMs(config.pingTimeout); + } + if (config.requestTimeout != null) { + clientOptions.requestTimeout = getDurationAsMs(config.requestTimeout); + } + if (config.sniffInterval) { + clientOptions.sniffInterval = getDurationAsMs(config.sniffInterval); + } + + // TODO: this can either be done here or by host in convertHost. + // Not sure which one we should choose. + if (config.username && config.password) { + clientOptions.auth = { + username: config.username, + password: config.password, + }; + } + + clientOptions.nodes = config.hosts.map((host) => convertHost(host, !scoped, config)); + + if (config.ssl) { + clientOptions.ssl = generateSslConfig( + config.ssl, + scoped && !config.ssl.alwaysPresentCertificate + ); + } + + return clientOptions; +} + +const generateSslConfig = ( + sslConfig: Required['ssl'], + ignoreCertAndKey: boolean +): TlsConnectionOptions => { + const ssl: TlsConnectionOptions = { + ca: sslConfig.certificateAuthorities, + }; + + const verificationMode = sslConfig.verificationMode; + switch (verificationMode) { + case 'none': + ssl.rejectUnauthorized = false; + break; + case 'certificate': + ssl.rejectUnauthorized = true; + // by default, NodeJS is checking the server identify + ssl.checkServerIdentity = () => undefined; + break; + case 'full': + ssl.rejectUnauthorized = true; + break; + default: + throw new Error(`Unknown ssl verificationMode: ${verificationMode}`); + } + + // Add client certificate and key if required by elasticsearch + if (!ignoreCertAndKey && sslConfig.certificate && sslConfig.key) { + ssl.cert = sslConfig.certificate; + ssl.key = sslConfig.key; + ssl.passphrase = sslConfig.keyPassphrase; + } + + return ssl; +}; + +const convertHost = ( + host: string, + needAuth: boolean, + { username, password }: ElasticsearchClientConfig +): NodeOptions => { + const url = new URL(host); + const isHTTPS = url.protocol === 'https:'; + url.port = url.port ?? isHTTPS ? '443' : '80'; + if (needAuth && username && password) { + url.username = username; + url.password = password; + } + + return { + url, + }; +}; + +const getDurationAsMs = (duration: number | Duration) => + typeof duration === 'number' ? duration : duration.asMilliseconds(); diff --git a/src/core/server/elasticsearch/client/client_facade.ts b/src/core/server/elasticsearch/client/client_facade.ts new file mode 100644 index 0000000000000..e60afd5dd3c9c --- /dev/null +++ b/src/core/server/elasticsearch/client/client_facade.ts @@ -0,0 +1,57 @@ +/* + * 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 { ApiResponse } from '@elastic/elasticsearch'; +import { + RequestBody, + RequestNDBody, + TransportRequestOptions, + TransportRequestPromise, +} from '@elastic/elasticsearch/lib/Transport'; +import * as RequestParams from '@elastic/elasticsearch/api/requestParams'; + +export interface ClientFacade { + bulk< + TResponse = Record, + TRequestBody extends RequestNDBody = Array>, + TContext = unknown + >( + params?: RequestParams.Bulk, + options?: TransportRequestOptions + ): TransportRequestPromise>; + + asyncSearch: { + delete, TContext = unknown>( + params?: RequestParams.AsyncSearchDelete, + options?: TransportRequestOptions + ): TransportRequestPromise>; + get, TContext = unknown>( + params?: RequestParams.AsyncSearchGet, + options?: TransportRequestOptions + ): TransportRequestPromise>; + submit< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.AsyncSearchSubmit, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; +} diff --git a/src/core/server/elasticsearch/client/client_wrapper.ts b/src/core/server/elasticsearch/client/client_wrapper.ts new file mode 100644 index 0000000000000..e270d118a89b4 --- /dev/null +++ b/src/core/server/elasticsearch/client/client_wrapper.ts @@ -0,0 +1,51 @@ +/* + * 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 '@elastic/elasticsearch'; +import { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport'; +import { Headers } from '../../http/router'; +import { ClientFacade } from './client_facade'; + +export const getClientFacade = (client: Client, headers: Headers = {}): ClientFacade => { + const addHeaders = (options?: TransportRequestOptions): TransportRequestOptions => { + if (!options) { + return { + headers, + }; + } + // TODO: do we need to throw in case of duplicates as it was done + // in legacy? - src/core/server/elasticsearch/scoped_cluster_client.ts:L88 + return { + ...options, + headers: { + ...options.headers, + ...headers, + }, + }; + }; + + return { + bulk: (params, options) => client.bulk(params, addHeaders(options)), + asyncSearch: { + delete: (params, options) => client.asyncSearch.delete(params, addHeaders(options)), + get: (params, options) => client.asyncSearch.get(params, addHeaders(options)), + submit: (params, options) => client.asyncSearch.submit(params, addHeaders(options)), + }, + }; +}; diff --git a/src/core/server/elasticsearch/client/cluster_client.ts b/src/core/server/elasticsearch/client/cluster_client.ts new file mode 100644 index 0000000000000..94f2cfc8d9a0f --- /dev/null +++ b/src/core/server/elasticsearch/client/cluster_client.ts @@ -0,0 +1,71 @@ +/* + * 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 '@elastic/elasticsearch'; +import { getClientFacade } from './client_wrapper'; +import { ClientFacade } from './client_facade'; +import { configureClient } from './configure_client'; +import { Logger } from '../../logging'; +import { GetAuthHeaders, isRealRequest } from '../../http'; +import { Headers } from '../../http/router'; +import { ElasticsearchClientConfig } from './client_config'; +import { ScopedClusterClient, IScopedClusterClient } from './scoped_cluster_client'; +import { ScopeableRequest } from './types'; +import { ensureRawRequest, filterHeaders } from '../../http/router'; + +const noop = () => undefined; + +interface IClusterClient { + asInternalUser: () => ClientFacade; + asScoped: (request: ScopeableRequest) => IScopedClusterClient; +} + +export class ClusterClient implements IClusterClient { + private readonly internalWrapper: ClientFacade; + private readonly scopedClient: Client; + + constructor( + private readonly config: ElasticsearchClientConfig, + private readonly log: Logger, // TODO: use when configuring the es client with logQueries + private readonly getAuthHeaders: GetAuthHeaders = noop + ) { + this.internalWrapper = getClientFacade(configureClient(config)); + this.scopedClient = configureClient(config, { scoped: true }); + } + + asInternalUser() { + return this.internalWrapper; + } + + asScoped(request: ScopeableRequest) { + const headers = this.getScopedHeaders(request); + const scopedWrapper = getClientFacade(this.scopedClient, headers); + return new ScopedClusterClient(this.internalWrapper, scopedWrapper); + } + + private getScopedHeaders(request: ScopeableRequest): Headers { + if (!isRealRequest(request)) { + return request?.headers ?? {}; + } + const authHeaders = this.getAuthHeaders(request); + const headers = ensureRawRequest(request).headers; + + return filterHeaders({ ...headers, ...authHeaders }, this.config.requestHeadersWhitelist); + } +} diff --git a/src/core/server/elasticsearch/client/configure_client.ts b/src/core/server/elasticsearch/client/configure_client.ts new file mode 100644 index 0000000000000..e7ae7674f5060 --- /dev/null +++ b/src/core/server/elasticsearch/client/configure_client.ts @@ -0,0 +1,31 @@ +/* + * 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 '@elastic/elasticsearch'; +import { parseClientOptions, ElasticsearchClientConfig } from './client_config'; + +export const configureClient = ( + config: ElasticsearchClientConfig, + { scoped = false }: { scoped?: boolean } = {} +): Client => { + const clientOptions = parseClientOptions(config, scoped); + const client = new Client(clientOptions); + // TODO: logQueries & co. + return client; +}; diff --git a/src/core/server/elasticsearch/client/index.ts b/src/core/server/elasticsearch/client/index.ts new file mode 100644 index 0000000000000..9880b336e76e5 --- /dev/null +++ b/src/core/server/elasticsearch/client/index.ts @@ -0,0 +1,18 @@ +/* + * 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. + */ diff --git a/src/core/server/elasticsearch/client/scoped_cluster_client.ts b/src/core/server/elasticsearch/client/scoped_cluster_client.ts new file mode 100644 index 0000000000000..7786963aec09e --- /dev/null +++ b/src/core/server/elasticsearch/client/scoped_cluster_client.ts @@ -0,0 +1,43 @@ +/* + * 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 { ClientWrapper } from './client_wrapper'; +import { ClientFacade } from './client_facade'; + +/** @public **/ +export interface IScopedClusterClient { + asInternalUser: () => ClientFacade; + asCurrentUser: () => ClientFacade; +} + +/** @internal **/ +export class ScopedClusterClient implements IScopedClusterClient { + constructor( + private readonly internalClient: ClientWrapper, + private readonly scopedClient: ClientWrapper + ) {} + + asInternalUser() { + return this.internalClient; + } + + asCurrentUser() { + return this.scopedClient; + } +} diff --git a/src/core/server/elasticsearch/client/types.ts b/src/core/server/elasticsearch/client/types.ts new file mode 100644 index 0000000000000..38e6acbb9323d --- /dev/null +++ b/src/core/server/elasticsearch/client/types.ts @@ -0,0 +1,39 @@ +/* + * 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 { LegacyRequest } from '../../http'; +import { Headers, KibanaRequest } from '../../http/router'; + +/** + * Fake request object created manually by Kibana plugins. + * @public + */ +export interface FakeRequest { + /** Headers used for authentication against Elasticsearch */ + headers: Headers; +} + +/** + A user credentials container. + * It accommodates the necessary auth credentials to impersonate the current user. + * + * @public + * See {@link KibanaRequest}. + */ +export type ScopeableRequest = KibanaRequest | LegacyRequest | FakeRequest; From 175e0cb902b6235476f7d178a01d021960503a68 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 25 Jun 2020 14:17:02 +0200 Subject: [PATCH 03/42] add logging --- .../elasticsearch/client/client_config.ts | 4 ++-- .../elasticsearch/client/cluster_client.ts | 6 +++--- .../elasticsearch/client/configure_client.ts | 19 +++++++++++++++++-- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/core/server/elasticsearch/client/client_config.ts b/src/core/server/elasticsearch/client/client_config.ts index 3b6a4d57c60d6..64a9234778b83 100644 --- a/src/core/server/elasticsearch/client/client_config.ts +++ b/src/core/server/elasticsearch/client/client_config.ts @@ -67,8 +67,8 @@ export function parseClientOptions( clientOptions.sniffInterval = getDurationAsMs(config.sniffInterval); } - // TODO: this can either be done here or by host in convertHost. - // Not sure which one we should choose. + // TODO: this can either be done globally here or by host in convertHost. + // Not sure which option is the best. if (config.username && config.password) { clientOptions.auth = { username: config.username, diff --git a/src/core/server/elasticsearch/client/cluster_client.ts b/src/core/server/elasticsearch/client/cluster_client.ts index 94f2cfc8d9a0f..c52b41072c473 100644 --- a/src/core/server/elasticsearch/client/cluster_client.ts +++ b/src/core/server/elasticsearch/client/cluster_client.ts @@ -42,11 +42,11 @@ export class ClusterClient implements IClusterClient { constructor( private readonly config: ElasticsearchClientConfig, - private readonly log: Logger, // TODO: use when configuring the es client with logQueries + logger: Logger, private readonly getAuthHeaders: GetAuthHeaders = noop ) { - this.internalWrapper = getClientFacade(configureClient(config)); - this.scopedClient = configureClient(config, { scoped: true }); + this.internalWrapper = getClientFacade(configureClient(config, { logger })); + this.scopedClient = configureClient(config, { logger, scoped: true }); } asInternalUser() { diff --git a/src/core/server/elasticsearch/client/configure_client.ts b/src/core/server/elasticsearch/client/configure_client.ts index e7ae7674f5060..74a5a7c7b0775 100644 --- a/src/core/server/elasticsearch/client/configure_client.ts +++ b/src/core/server/elasticsearch/client/configure_client.ts @@ -18,14 +18,29 @@ */ import { Client } from '@elastic/elasticsearch'; +import { Logger } from '../../logging'; import { parseClientOptions, ElasticsearchClientConfig } from './client_config'; export const configureClient = ( config: ElasticsearchClientConfig, - { scoped = false }: { scoped?: boolean } = {} + { logger, scoped = false }: { logger: Logger; scoped?: boolean } ): Client => { const clientOptions = parseClientOptions(config, scoped); const client = new Client(clientOptions); - // TODO: logQueries & co. + + client.on('response', (err, event) => { + if (err) { + logger.error(`${err.name}: ${err.message}`); + } else if (config.logQueries) { + const params = event.meta.request.params; + logger.debug( + `${event.statusCode}\n${params.method} ${params.path}\n${params.querystring?.trim() ?? ''}`, + { + tags: ['query'], + } + ); + } + }); + return client; }; From 24ac36b17a8bf53b299a1195f210066b3aa57ecf Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Mon, 29 Jun 2020 14:56:40 +0200 Subject: [PATCH 04/42] add generation script for client facade API and implementation --- scripts/generate_es_client.js | 21 + .../elasticsearch/client/client_facade.ts | 1723 ++++++++++++++++- .../elasticsearch/client/client_wrapper.ts | 448 ++++- .../client/scoped_cluster_client.ts | 5 +- src/dev/generate_es_client.ts | 150 ++ 5 files changed, 2332 insertions(+), 15 deletions(-) create mode 100644 scripts/generate_es_client.js create mode 100644 src/dev/generate_es_client.ts diff --git a/scripts/generate_es_client.js b/scripts/generate_es_client.js new file mode 100644 index 0000000000000..5d7845c933bff --- /dev/null +++ b/scripts/generate_es_client.js @@ -0,0 +1,21 @@ +/* + * 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. + */ + +require('../src/setup_node_env'); +require('../src/dev/generate_es_client'); diff --git a/src/core/server/elasticsearch/client/client_facade.ts b/src/core/server/elasticsearch/client/client_facade.ts index e60afd5dd3c9c..cbc7841bc2c69 100644 --- a/src/core/server/elasticsearch/client/client_facade.ts +++ b/src/core/server/elasticsearch/client/client_facade.ts @@ -27,6 +27,31 @@ import { import * as RequestParams from '@elastic/elasticsearch/api/requestParams'; export interface ClientFacade { + /* GENERATED */ + asyncSearch: { + delete, TContext = unknown>( + params?: RequestParams.AsyncSearchDelete, + options?: TransportRequestOptions + ): TransportRequestPromise>; + get, TContext = unknown>( + params?: RequestParams.AsyncSearchGet, + options?: TransportRequestOptions + ): TransportRequestPromise>; + submit< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.AsyncSearchSubmit, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + autoscaling: { + getAutoscalingDecision, TContext = unknown>( + params?: RequestParams.AutoscalingGetAutoscalingDecision, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; bulk< TResponse = Record, TRequestBody extends RequestNDBody = Array>, @@ -35,23 +60,1705 @@ export interface ClientFacade { params?: RequestParams.Bulk, options?: TransportRequestOptions ): TransportRequestPromise>; - - asyncSearch: { - delete, TContext = unknown>( - params?: RequestParams.AsyncSearchDelete, + cat: { + aliases, TContext = unknown>( + params?: RequestParams.CatAliases, options?: TransportRequestOptions ): TransportRequestPromise>; - get, TContext = unknown>( - params?: RequestParams.AsyncSearchGet, + allocation, TContext = unknown>( + params?: RequestParams.CatAllocation, options?: TransportRequestOptions ): TransportRequestPromise>; - submit< + count, TContext = unknown>( + params?: RequestParams.CatCount, + options?: TransportRequestOptions + ): TransportRequestPromise>; + fielddata, TContext = unknown>( + params?: RequestParams.CatFielddata, + options?: TransportRequestOptions + ): TransportRequestPromise>; + health, TContext = unknown>( + params?: RequestParams.CatHealth, + options?: TransportRequestOptions + ): TransportRequestPromise>; + help, TContext = unknown>( + params?: RequestParams.CatHelp, + options?: TransportRequestOptions + ): TransportRequestPromise>; + indices, TContext = unknown>( + params?: RequestParams.CatIndices, + options?: TransportRequestOptions + ): TransportRequestPromise>; + master, TContext = unknown>( + params?: RequestParams.CatMaster, + options?: TransportRequestOptions + ): TransportRequestPromise>; + mlDataFrameAnalytics, TContext = unknown>( + params?: RequestParams.CatMlDataFrameAnalytics, + options?: TransportRequestOptions + ): TransportRequestPromise>; + mlDatafeeds, TContext = unknown>( + params?: RequestParams.CatMlDatafeeds, + options?: TransportRequestOptions + ): TransportRequestPromise>; + mlJobs, TContext = unknown>( + params?: RequestParams.CatMlJobs, + options?: TransportRequestOptions + ): TransportRequestPromise>; + mlTrainedModels, TContext = unknown>( + params?: RequestParams.CatMlTrainedModels, + options?: TransportRequestOptions + ): TransportRequestPromise>; + nodeattrs, TContext = unknown>( + params?: RequestParams.CatNodeattrs, + options?: TransportRequestOptions + ): TransportRequestPromise>; + nodes, TContext = unknown>( + params?: RequestParams.CatNodes, + options?: TransportRequestOptions + ): TransportRequestPromise>; + pendingTasks, TContext = unknown>( + params?: RequestParams.CatPendingTasks, + options?: TransportRequestOptions + ): TransportRequestPromise>; + plugins, TContext = unknown>( + params?: RequestParams.CatPlugins, + options?: TransportRequestOptions + ): TransportRequestPromise>; + recovery, TContext = unknown>( + params?: RequestParams.CatRecovery, + options?: TransportRequestOptions + ): TransportRequestPromise>; + repositories, TContext = unknown>( + params?: RequestParams.CatRepositories, + options?: TransportRequestOptions + ): TransportRequestPromise>; + segments, TContext = unknown>( + params?: RequestParams.CatSegments, + options?: TransportRequestOptions + ): TransportRequestPromise>; + shards, TContext = unknown>( + params?: RequestParams.CatShards, + options?: TransportRequestOptions + ): TransportRequestPromise>; + snapshots, TContext = unknown>( + params?: RequestParams.CatSnapshots, + options?: TransportRequestOptions + ): TransportRequestPromise>; + tasks, TContext = unknown>( + params?: RequestParams.CatTasks, + options?: TransportRequestOptions + ): TransportRequestPromise>; + templates, TContext = unknown>( + params?: RequestParams.CatTemplates, + options?: TransportRequestOptions + ): TransportRequestPromise>; + threadPool, TContext = unknown>( + params?: RequestParams.CatThreadPool, + options?: TransportRequestOptions + ): TransportRequestPromise>; + transforms, TContext = unknown>( + params?: RequestParams.CatTransforms, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + ccr: { + deleteAutoFollowPattern, TContext = unknown>( + params?: RequestParams.CcrDeleteAutoFollowPattern, + options?: TransportRequestOptions + ): TransportRequestPromise>; + follow< TResponse = Record, TRequestBody extends RequestBody = Record, TContext = unknown >( - params?: RequestParams.AsyncSearchSubmit, + params?: RequestParams.CcrFollow, + options?: TransportRequestOptions + ): TransportRequestPromise>; + followInfo, TContext = unknown>( + params?: RequestParams.CcrFollowInfo, + options?: TransportRequestOptions + ): TransportRequestPromise>; + followStats, TContext = unknown>( + params?: RequestParams.CcrFollowStats, + options?: TransportRequestOptions + ): TransportRequestPromise>; + forgetFollower< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.CcrForgetFollower, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getAutoFollowPattern, TContext = unknown>( + params?: RequestParams.CcrGetAutoFollowPattern, + options?: TransportRequestOptions + ): TransportRequestPromise>; + pauseAutoFollowPattern, TContext = unknown>( + params?: RequestParams.CcrPauseAutoFollowPattern, + options?: TransportRequestOptions + ): TransportRequestPromise>; + pauseFollow, TContext = unknown>( + params?: RequestParams.CcrPauseFollow, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putAutoFollowPattern< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.CcrPutAutoFollowPattern, + options?: TransportRequestOptions + ): TransportRequestPromise>; + resumeAutoFollowPattern, TContext = unknown>( + params?: RequestParams.CcrResumeAutoFollowPattern, + options?: TransportRequestOptions + ): TransportRequestPromise>; + resumeFollow< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.CcrResumeFollow, + options?: TransportRequestOptions + ): TransportRequestPromise>; + stats, TContext = unknown>( + params?: RequestParams.CcrStats, + options?: TransportRequestOptions + ): TransportRequestPromise>; + unfollow, TContext = unknown>( + params?: RequestParams.CcrUnfollow, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + clearScroll< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.ClearScroll, + options?: TransportRequestOptions + ): TransportRequestPromise>; + cluster: { + allocationExplain< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.ClusterAllocationExplain, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteComponentTemplate, TContext = unknown>( + params?: RequestParams.ClusterDeleteComponentTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getComponentTemplate, TContext = unknown>( + params?: RequestParams.ClusterGetComponentTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getSettings, TContext = unknown>( + params?: RequestParams.ClusterGetSettings, + options?: TransportRequestOptions + ): TransportRequestPromise>; + health, TContext = unknown>( + params?: RequestParams.ClusterHealth, + options?: TransportRequestOptions + ): TransportRequestPromise>; + pendingTasks, TContext = unknown>( + params?: RequestParams.ClusterPendingTasks, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putComponentTemplate< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.ClusterPutComponentTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putSettings< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.ClusterPutSettings, + options?: TransportRequestOptions + ): TransportRequestPromise>; + remoteInfo, TContext = unknown>( + params?: RequestParams.ClusterRemoteInfo, + options?: TransportRequestOptions + ): TransportRequestPromise>; + reroute< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.ClusterReroute, + options?: TransportRequestOptions + ): TransportRequestPromise>; + state, TContext = unknown>( + params?: RequestParams.ClusterState, + options?: TransportRequestOptions + ): TransportRequestPromise>; + stats, TContext = unknown>( + params?: RequestParams.ClusterStats, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + count< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.Count, + options?: TransportRequestOptions + ): TransportRequestPromise>; + create< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.Create, + options?: TransportRequestOptions + ): TransportRequestPromise>; + delete, TContext = unknown>( + params?: RequestParams.Delete, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteByQuery< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.DeleteByQuery, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteByQueryRethrottle, TContext = unknown>( + params?: RequestParams.DeleteByQueryRethrottle, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteScript, TContext = unknown>( + params?: RequestParams.DeleteScript, + options?: TransportRequestOptions + ): TransportRequestPromise>; + enrich: { + deletePolicy, TContext = unknown>( + params?: RequestParams.EnrichDeletePolicy, + options?: TransportRequestOptions + ): TransportRequestPromise>; + executePolicy, TContext = unknown>( + params?: RequestParams.EnrichExecutePolicy, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getPolicy, TContext = unknown>( + params?: RequestParams.EnrichGetPolicy, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putPolicy< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.EnrichPutPolicy, + options?: TransportRequestOptions + ): TransportRequestPromise>; + stats, TContext = unknown>( + params?: RequestParams.EnrichStats, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + eql: { + search< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.EqlSearch, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + exists, TContext = unknown>( + params?: RequestParams.Exists, + options?: TransportRequestOptions + ): TransportRequestPromise>; + existsSource, TContext = unknown>( + params?: RequestParams.ExistsSource, + options?: TransportRequestOptions + ): TransportRequestPromise>; + explain< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.Explain, + options?: TransportRequestOptions + ): TransportRequestPromise>; + fieldCaps, TContext = unknown>( + params?: RequestParams.FieldCaps, + options?: TransportRequestOptions + ): TransportRequestPromise>; + get, TContext = unknown>( + params?: RequestParams.Get, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getScript, TContext = unknown>( + params?: RequestParams.GetScript, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getScriptContext, TContext = unknown>( + params?: RequestParams.GetScriptContext, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getScriptLanguages, TContext = unknown>( + params?: RequestParams.GetScriptLanguages, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getSource, TContext = unknown>( + params?: RequestParams.GetSource, + options?: TransportRequestOptions + ): TransportRequestPromise>; + graph: { + explore< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.GraphExplore, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + ilm: { + deleteLifecycle, TContext = unknown>( + params?: RequestParams.IlmDeleteLifecycle, + options?: TransportRequestOptions + ): TransportRequestPromise>; + explainLifecycle, TContext = unknown>( + params?: RequestParams.IlmExplainLifecycle, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getLifecycle, TContext = unknown>( + params?: RequestParams.IlmGetLifecycle, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getStatus, TContext = unknown>( + params?: RequestParams.IlmGetStatus, + options?: TransportRequestOptions + ): TransportRequestPromise>; + moveToStep< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IlmMoveToStep, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putLifecycle< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IlmPutLifecycle, + options?: TransportRequestOptions + ): TransportRequestPromise>; + removePolicy, TContext = unknown>( + params?: RequestParams.IlmRemovePolicy, + options?: TransportRequestOptions + ): TransportRequestPromise>; + retry, TContext = unknown>( + params?: RequestParams.IlmRetry, + options?: TransportRequestOptions + ): TransportRequestPromise>; + start, TContext = unknown>( + params?: RequestParams.IlmStart, + options?: TransportRequestOptions + ): TransportRequestPromise>; + stop, TContext = unknown>( + params?: RequestParams.IlmStop, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + index< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.Index, + options?: TransportRequestOptions + ): TransportRequestPromise>; + indices: { + analyze< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IndicesAnalyze, + options?: TransportRequestOptions + ): TransportRequestPromise>; + clearCache, TContext = unknown>( + params?: RequestParams.IndicesClearCache, + options?: TransportRequestOptions + ): TransportRequestPromise>; + clone< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IndicesClone, + options?: TransportRequestOptions + ): TransportRequestPromise>; + close, TContext = unknown>( + params?: RequestParams.IndicesClose, + options?: TransportRequestOptions + ): TransportRequestPromise>; + create< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IndicesCreate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + createDataStream< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IndicesCreateDataStream, + options?: TransportRequestOptions + ): TransportRequestPromise>; + delete, TContext = unknown>( + params?: RequestParams.IndicesDelete, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteAlias, TContext = unknown>( + params?: RequestParams.IndicesDeleteAlias, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteDataStream, TContext = unknown>( + params?: RequestParams.IndicesDeleteDataStream, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteTemplate, TContext = unknown>( + params?: RequestParams.IndicesDeleteTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + exists, TContext = unknown>( + params?: RequestParams.IndicesExists, + options?: TransportRequestOptions + ): TransportRequestPromise>; + existsAlias, TContext = unknown>( + params?: RequestParams.IndicesExistsAlias, + options?: TransportRequestOptions + ): TransportRequestPromise>; + existsTemplate, TContext = unknown>( + params?: RequestParams.IndicesExistsTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + existsType, TContext = unknown>( + params?: RequestParams.IndicesExistsType, + options?: TransportRequestOptions + ): TransportRequestPromise>; + flush, TContext = unknown>( + params?: RequestParams.IndicesFlush, + options?: TransportRequestOptions + ): TransportRequestPromise>; + flushSynced, TContext = unknown>( + params?: RequestParams.IndicesFlushSynced, + options?: TransportRequestOptions + ): TransportRequestPromise>; + forcemerge, TContext = unknown>( + params?: RequestParams.IndicesForcemerge, + options?: TransportRequestOptions + ): TransportRequestPromise>; + freeze, TContext = unknown>( + params?: RequestParams.IndicesFreeze, + options?: TransportRequestOptions + ): TransportRequestPromise>; + get, TContext = unknown>( + params?: RequestParams.IndicesGet, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getAlias, TContext = unknown>( + params?: RequestParams.IndicesGetAlias, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getDataStreams, TContext = unknown>( + params?: RequestParams.IndicesGetDataStreams, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getFieldMapping, TContext = unknown>( + params?: RequestParams.IndicesGetFieldMapping, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getMapping, TContext = unknown>( + params?: RequestParams.IndicesGetMapping, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getSettings, TContext = unknown>( + params?: RequestParams.IndicesGetSettings, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getTemplate, TContext = unknown>( + params?: RequestParams.IndicesGetTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getUpgrade, TContext = unknown>( + params?: RequestParams.IndicesGetUpgrade, + options?: TransportRequestOptions + ): TransportRequestPromise>; + open, TContext = unknown>( + params?: RequestParams.IndicesOpen, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putAlias< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IndicesPutAlias, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putMapping< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IndicesPutMapping, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putSettings< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IndicesPutSettings, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putTemplate< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IndicesPutTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + recovery, TContext = unknown>( + params?: RequestParams.IndicesRecovery, + options?: TransportRequestOptions + ): TransportRequestPromise>; + refresh, TContext = unknown>( + params?: RequestParams.IndicesRefresh, + options?: TransportRequestOptions + ): TransportRequestPromise>; + reloadSearchAnalyzers, TContext = unknown>( + params?: RequestParams.IndicesReloadSearchAnalyzers, + options?: TransportRequestOptions + ): TransportRequestPromise>; + rollover< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IndicesRollover, + options?: TransportRequestOptions + ): TransportRequestPromise>; + segments, TContext = unknown>( + params?: RequestParams.IndicesSegments, + options?: TransportRequestOptions + ): TransportRequestPromise>; + shardStores, TContext = unknown>( + params?: RequestParams.IndicesShardStores, + options?: TransportRequestOptions + ): TransportRequestPromise>; + shrink< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IndicesShrink, + options?: TransportRequestOptions + ): TransportRequestPromise>; + split< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IndicesSplit, + options?: TransportRequestOptions + ): TransportRequestPromise>; + stats, TContext = unknown>( + params?: RequestParams.IndicesStats, + options?: TransportRequestOptions + ): TransportRequestPromise>; + unfreeze, TContext = unknown>( + params?: RequestParams.IndicesUnfreeze, + options?: TransportRequestOptions + ): TransportRequestPromise>; + updateAliases< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IndicesUpdateAliases, + options?: TransportRequestOptions + ): TransportRequestPromise>; + upgrade, TContext = unknown>( + params?: RequestParams.IndicesUpgrade, + options?: TransportRequestOptions + ): TransportRequestPromise>; + validateQuery< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IndicesValidateQuery, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + info, TContext = unknown>( + params?: RequestParams.Info, + options?: TransportRequestOptions + ): TransportRequestPromise>; + ingest: { + deletePipeline, TContext = unknown>( + params?: RequestParams.IngestDeletePipeline, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getPipeline, TContext = unknown>( + params?: RequestParams.IngestGetPipeline, + options?: TransportRequestOptions + ): TransportRequestPromise>; + processorGrok, TContext = unknown>( + params?: RequestParams.IngestProcessorGrok, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putPipeline< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IngestPutPipeline, + options?: TransportRequestOptions + ): TransportRequestPromise>; + simulate< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IngestSimulate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + license: { + delete, TContext = unknown>( + params?: RequestParams.LicenseDelete, + options?: TransportRequestOptions + ): TransportRequestPromise>; + get, TContext = unknown>( + params?: RequestParams.LicenseGet, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getBasicStatus, TContext = unknown>( + params?: RequestParams.LicenseGetBasicStatus, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getTrialStatus, TContext = unknown>( + params?: RequestParams.LicenseGetTrialStatus, + options?: TransportRequestOptions + ): TransportRequestPromise>; + post< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.LicensePost, + options?: TransportRequestOptions + ): TransportRequestPromise>; + postStartBasic, TContext = unknown>( + params?: RequestParams.LicensePostStartBasic, + options?: TransportRequestOptions + ): TransportRequestPromise>; + postStartTrial, TContext = unknown>( + params?: RequestParams.LicensePostStartTrial, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + mget< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.Mget, + options?: TransportRequestOptions + ): TransportRequestPromise>; + migration: { + deprecations, TContext = unknown>( + params?: RequestParams.MigrationDeprecations, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + ml: { + closeJob< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlCloseJob, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteCalendar, TContext = unknown>( + params?: RequestParams.MlDeleteCalendar, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteCalendarEvent, TContext = unknown>( + params?: RequestParams.MlDeleteCalendarEvent, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteCalendarJob, TContext = unknown>( + params?: RequestParams.MlDeleteCalendarJob, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteDataFrameAnalytics, TContext = unknown>( + params?: RequestParams.MlDeleteDataFrameAnalytics, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteDatafeed, TContext = unknown>( + params?: RequestParams.MlDeleteDatafeed, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteExpiredData, TContext = unknown>( + params?: RequestParams.MlDeleteExpiredData, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteFilter, TContext = unknown>( + params?: RequestParams.MlDeleteFilter, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteForecast, TContext = unknown>( + params?: RequestParams.MlDeleteForecast, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteJob, TContext = unknown>( + params?: RequestParams.MlDeleteJob, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteModelSnapshot, TContext = unknown>( + params?: RequestParams.MlDeleteModelSnapshot, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteTrainedModel, TContext = unknown>( + params?: RequestParams.MlDeleteTrainedModel, + options?: TransportRequestOptions + ): TransportRequestPromise>; + estimateModelMemory< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlEstimateModelMemory, + options?: TransportRequestOptions + ): TransportRequestPromise>; + evaluateDataFrame< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlEvaluateDataFrame, + options?: TransportRequestOptions + ): TransportRequestPromise>; + explainDataFrameAnalytics< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlExplainDataFrameAnalytics, + options?: TransportRequestOptions + ): TransportRequestPromise>; + findFileStructure< + TResponse = Record, + TRequestBody extends RequestNDBody = Array>, + TContext = unknown + >( + params?: RequestParams.MlFindFileStructure, + options?: TransportRequestOptions + ): TransportRequestPromise>; + flushJob< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlFlushJob, + options?: TransportRequestOptions + ): TransportRequestPromise>; + forecast, TContext = unknown>( + params?: RequestParams.MlForecast, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getBuckets< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlGetBuckets, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getCalendarEvents, TContext = unknown>( + params?: RequestParams.MlGetCalendarEvents, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getCalendars< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlGetCalendars, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getCategories< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlGetCategories, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getDataFrameAnalytics, TContext = unknown>( + params?: RequestParams.MlGetDataFrameAnalytics, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getDataFrameAnalyticsStats, TContext = unknown>( + params?: RequestParams.MlGetDataFrameAnalyticsStats, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getDatafeedStats, TContext = unknown>( + params?: RequestParams.MlGetDatafeedStats, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getDatafeeds, TContext = unknown>( + params?: RequestParams.MlGetDatafeeds, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getFilters, TContext = unknown>( + params?: RequestParams.MlGetFilters, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getInfluencers< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlGetInfluencers, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getJobStats, TContext = unknown>( + params?: RequestParams.MlGetJobStats, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getJobs, TContext = unknown>( + params?: RequestParams.MlGetJobs, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getModelSnapshots< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlGetModelSnapshots, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getOverallBuckets< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlGetOverallBuckets, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getRecords< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlGetRecords, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getTrainedModels, TContext = unknown>( + params?: RequestParams.MlGetTrainedModels, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getTrainedModelsStats, TContext = unknown>( + params?: RequestParams.MlGetTrainedModelsStats, + options?: TransportRequestOptions + ): TransportRequestPromise>; + info, TContext = unknown>( + params?: RequestParams.MlInfo, + options?: TransportRequestOptions + ): TransportRequestPromise>; + openJob, TContext = unknown>( + params?: RequestParams.MlOpenJob, + options?: TransportRequestOptions + ): TransportRequestPromise>; + postCalendarEvents< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlPostCalendarEvents, + options?: TransportRequestOptions + ): TransportRequestPromise>; + postData< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlPostData, + options?: TransportRequestOptions + ): TransportRequestPromise>; + previewDatafeed, TContext = unknown>( + params?: RequestParams.MlPreviewDatafeed, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putCalendar< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlPutCalendar, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putCalendarJob, TContext = unknown>( + params?: RequestParams.MlPutCalendarJob, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putDataFrameAnalytics< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlPutDataFrameAnalytics, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putDatafeed< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlPutDatafeed, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putFilter< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlPutFilter, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putJob< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlPutJob, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putTrainedModel< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlPutTrainedModel, + options?: TransportRequestOptions + ): TransportRequestPromise>; + revertModelSnapshot< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlRevertModelSnapshot, + options?: TransportRequestOptions + ): TransportRequestPromise>; + setUpgradeMode, TContext = unknown>( + params?: RequestParams.MlSetUpgradeMode, + options?: TransportRequestOptions + ): TransportRequestPromise>; + startDataFrameAnalytics< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlStartDataFrameAnalytics, + options?: TransportRequestOptions + ): TransportRequestPromise>; + startDatafeed< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlStartDatafeed, + options?: TransportRequestOptions + ): TransportRequestPromise>; + stopDataFrameAnalytics< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlStopDataFrameAnalytics, + options?: TransportRequestOptions + ): TransportRequestPromise>; + stopDatafeed, TContext = unknown>( + params?: RequestParams.MlStopDatafeed, + options?: TransportRequestOptions + ): TransportRequestPromise>; + updateDatafeed< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlUpdateDatafeed, + options?: TransportRequestOptions + ): TransportRequestPromise>; + updateFilter< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlUpdateFilter, + options?: TransportRequestOptions + ): TransportRequestPromise>; + updateJob< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlUpdateJob, + options?: TransportRequestOptions + ): TransportRequestPromise>; + updateModelSnapshot< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlUpdateModelSnapshot, + options?: TransportRequestOptions + ): TransportRequestPromise>; + validate< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlValidate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + validateDetector< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlValidateDetector, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + monitoring: { + bulk< + TResponse = Record, + TRequestBody extends RequestNDBody = Array>, + TContext = unknown + >( + params?: RequestParams.MonitoringBulk, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + msearch< + TResponse = Record, + TRequestBody extends RequestNDBody = Array>, + TContext = unknown + >( + params?: RequestParams.Msearch, + options?: TransportRequestOptions + ): TransportRequestPromise>; + msearchTemplate< + TResponse = Record, + TRequestBody extends RequestNDBody = Array>, + TContext = unknown + >( + params?: RequestParams.MsearchTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + mtermvectors< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.Mtermvectors, + options?: TransportRequestOptions + ): TransportRequestPromise>; + nodes: { + hotThreads, TContext = unknown>( + params?: RequestParams.NodesHotThreads, + options?: TransportRequestOptions + ): TransportRequestPromise>; + info, TContext = unknown>( + params?: RequestParams.NodesInfo, + options?: TransportRequestOptions + ): TransportRequestPromise>; + reloadSecureSettings< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.NodesReloadSecureSettings, + options?: TransportRequestOptions + ): TransportRequestPromise>; + stats, TContext = unknown>( + params?: RequestParams.NodesStats, + options?: TransportRequestOptions + ): TransportRequestPromise>; + usage, TContext = unknown>( + params?: RequestParams.NodesUsage, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + ping, TContext = unknown>( + params?: RequestParams.Ping, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putScript< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.PutScript, + options?: TransportRequestOptions + ): TransportRequestPromise>; + rankEval< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.RankEval, + options?: TransportRequestOptions + ): TransportRequestPromise>; + reindex< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.Reindex, + options?: TransportRequestOptions + ): TransportRequestPromise>; + reindexRethrottle, TContext = unknown>( + params?: RequestParams.ReindexRethrottle, + options?: TransportRequestOptions + ): TransportRequestPromise>; + renderSearchTemplate< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.RenderSearchTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + rollup: { + deleteJob, TContext = unknown>( + params?: RequestParams.RollupDeleteJob, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getJobs, TContext = unknown>( + params?: RequestParams.RollupGetJobs, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getRollupCaps, TContext = unknown>( + params?: RequestParams.RollupGetRollupCaps, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getRollupIndexCaps, TContext = unknown>( + params?: RequestParams.RollupGetRollupIndexCaps, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putJob< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.RollupPutJob, + options?: TransportRequestOptions + ): TransportRequestPromise>; + rollupSearch< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.RollupRollupSearch, + options?: TransportRequestOptions + ): TransportRequestPromise>; + startJob, TContext = unknown>( + params?: RequestParams.RollupStartJob, + options?: TransportRequestOptions + ): TransportRequestPromise>; + stopJob, TContext = unknown>( + params?: RequestParams.RollupStopJob, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + scriptsPainlessExecute< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.ScriptsPainlessExecute, + options?: TransportRequestOptions + ): TransportRequestPromise>; + scroll< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.Scroll, + options?: TransportRequestOptions + ): TransportRequestPromise>; + search< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.Search, + options?: TransportRequestOptions + ): TransportRequestPromise>; + searchShards, TContext = unknown>( + params?: RequestParams.SearchShards, + options?: TransportRequestOptions + ): TransportRequestPromise>; + searchTemplate< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SearchTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + security: { + authenticate, TContext = unknown>( + params?: RequestParams.SecurityAuthenticate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + changePassword< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SecurityChangePassword, + options?: TransportRequestOptions + ): TransportRequestPromise>; + clearCachedRealms, TContext = unknown>( + params?: RequestParams.SecurityClearCachedRealms, + options?: TransportRequestOptions + ): TransportRequestPromise>; + clearCachedRoles, TContext = unknown>( + params?: RequestParams.SecurityClearCachedRoles, + options?: TransportRequestOptions + ): TransportRequestPromise>; + createApiKey< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SecurityCreateApiKey, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deletePrivileges, TContext = unknown>( + params?: RequestParams.SecurityDeletePrivileges, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteRole, TContext = unknown>( + params?: RequestParams.SecurityDeleteRole, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteRoleMapping, TContext = unknown>( + params?: RequestParams.SecurityDeleteRoleMapping, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteUser, TContext = unknown>( + params?: RequestParams.SecurityDeleteUser, + options?: TransportRequestOptions + ): TransportRequestPromise>; + disableUser, TContext = unknown>( + params?: RequestParams.SecurityDisableUser, + options?: TransportRequestOptions + ): TransportRequestPromise>; + enableUser, TContext = unknown>( + params?: RequestParams.SecurityEnableUser, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getApiKey, TContext = unknown>( + params?: RequestParams.SecurityGetApiKey, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getBuiltinPrivileges, TContext = unknown>( + params?: RequestParams.SecurityGetBuiltinPrivileges, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getPrivileges, TContext = unknown>( + params?: RequestParams.SecurityGetPrivileges, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getRole, TContext = unknown>( + params?: RequestParams.SecurityGetRole, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getRoleMapping, TContext = unknown>( + params?: RequestParams.SecurityGetRoleMapping, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getToken< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SecurityGetToken, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getUser, TContext = unknown>( + params?: RequestParams.SecurityGetUser, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getUserPrivileges, TContext = unknown>( + params?: RequestParams.SecurityGetUserPrivileges, + options?: TransportRequestOptions + ): TransportRequestPromise>; + hasPrivileges< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SecurityHasPrivileges, + options?: TransportRequestOptions + ): TransportRequestPromise>; + invalidateApiKey< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SecurityInvalidateApiKey, + options?: TransportRequestOptions + ): TransportRequestPromise>; + invalidateToken< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SecurityInvalidateToken, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putPrivileges< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SecurityPutPrivileges, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putRole< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SecurityPutRole, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putRoleMapping< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SecurityPutRoleMapping, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putUser< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SecurityPutUser, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + slm: { + deleteLifecycle, TContext = unknown>( + params?: RequestParams.SlmDeleteLifecycle, + options?: TransportRequestOptions + ): TransportRequestPromise>; + executeLifecycle, TContext = unknown>( + params?: RequestParams.SlmExecuteLifecycle, + options?: TransportRequestOptions + ): TransportRequestPromise>; + executeRetention, TContext = unknown>( + params?: RequestParams.SlmExecuteRetention, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getLifecycle, TContext = unknown>( + params?: RequestParams.SlmGetLifecycle, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getStats, TContext = unknown>( + params?: RequestParams.SlmGetStats, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getStatus, TContext = unknown>( + params?: RequestParams.SlmGetStatus, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putLifecycle< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SlmPutLifecycle, + options?: TransportRequestOptions + ): TransportRequestPromise>; + start, TContext = unknown>( + params?: RequestParams.SlmStart, + options?: TransportRequestOptions + ): TransportRequestPromise>; + stop, TContext = unknown>( + params?: RequestParams.SlmStop, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + snapshot: { + cleanupRepository, TContext = unknown>( + params?: RequestParams.SnapshotCleanupRepository, + options?: TransportRequestOptions + ): TransportRequestPromise>; + create< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SnapshotCreate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + createRepository< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SnapshotCreateRepository, + options?: TransportRequestOptions + ): TransportRequestPromise>; + delete, TContext = unknown>( + params?: RequestParams.SnapshotDelete, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteRepository, TContext = unknown>( + params?: RequestParams.SnapshotDeleteRepository, + options?: TransportRequestOptions + ): TransportRequestPromise>; + get, TContext = unknown>( + params?: RequestParams.SnapshotGet, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getRepository, TContext = unknown>( + params?: RequestParams.SnapshotGetRepository, + options?: TransportRequestOptions + ): TransportRequestPromise>; + restore< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SnapshotRestore, + options?: TransportRequestOptions + ): TransportRequestPromise>; + status, TContext = unknown>( + params?: RequestParams.SnapshotStatus, + options?: TransportRequestOptions + ): TransportRequestPromise>; + verifyRepository, TContext = unknown>( + params?: RequestParams.SnapshotVerifyRepository, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + sql: { + clearCursor< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SqlClearCursor, + options?: TransportRequestOptions + ): TransportRequestPromise>; + query< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SqlQuery, + options?: TransportRequestOptions + ): TransportRequestPromise>; + translate< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SqlTranslate, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + ssl: { + certificates, TContext = unknown>( + params?: RequestParams.SslCertificates, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + tasks: { + cancel, TContext = unknown>( + params?: RequestParams.TasksCancel, + options?: TransportRequestOptions + ): TransportRequestPromise>; + get, TContext = unknown>( + params?: RequestParams.TasksGet, + options?: TransportRequestOptions + ): TransportRequestPromise>; + list, TContext = unknown>( + params?: RequestParams.TasksList, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + termvectors< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.Termvectors, + options?: TransportRequestOptions + ): TransportRequestPromise>; + transform: { + deleteTransform, TContext = unknown>( + params?: RequestParams.TransformDeleteTransform, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getTransform, TContext = unknown>( + params?: RequestParams.TransformGetTransform, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getTransformStats, TContext = unknown>( + params?: RequestParams.TransformGetTransformStats, + options?: TransportRequestOptions + ): TransportRequestPromise>; + previewTransform< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.TransformPreviewTransform, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putTransform< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.TransformPutTransform, + options?: TransportRequestOptions + ): TransportRequestPromise>; + startTransform, TContext = unknown>( + params?: RequestParams.TransformStartTransform, + options?: TransportRequestOptions + ): TransportRequestPromise>; + stopTransform, TContext = unknown>( + params?: RequestParams.TransformStopTransform, + options?: TransportRequestOptions + ): TransportRequestPromise>; + updateTransform< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.TransformUpdateTransform, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + update< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.Update, + options?: TransportRequestOptions + ): TransportRequestPromise>; + updateByQuery< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.UpdateByQuery, + options?: TransportRequestOptions + ): TransportRequestPromise>; + updateByQueryRethrottle, TContext = unknown>( + params?: RequestParams.UpdateByQueryRethrottle, + options?: TransportRequestOptions + ): TransportRequestPromise>; + watcher: { + ackWatch, TContext = unknown>( + params?: RequestParams.WatcherAckWatch, + options?: TransportRequestOptions + ): TransportRequestPromise>; + activateWatch, TContext = unknown>( + params?: RequestParams.WatcherActivateWatch, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deactivateWatch, TContext = unknown>( + params?: RequestParams.WatcherDeactivateWatch, + options?: TransportRequestOptions + ): TransportRequestPromise>; + deleteWatch, TContext = unknown>( + params?: RequestParams.WatcherDeleteWatch, + options?: TransportRequestOptions + ): TransportRequestPromise>; + executeWatch< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.WatcherExecuteWatch, + options?: TransportRequestOptions + ): TransportRequestPromise>; + getWatch, TContext = unknown>( + params?: RequestParams.WatcherGetWatch, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putWatch< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.WatcherPutWatch, + options?: TransportRequestOptions + ): TransportRequestPromise>; + start, TContext = unknown>( + params?: RequestParams.WatcherStart, + options?: TransportRequestOptions + ): TransportRequestPromise>; + stats, TContext = unknown>( + params?: RequestParams.WatcherStats, + options?: TransportRequestOptions + ): TransportRequestPromise>; + stop, TContext = unknown>( + params?: RequestParams.WatcherStop, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; + xpack: { + info, TContext = unknown>( + params?: RequestParams.XpackInfo, + options?: TransportRequestOptions + ): TransportRequestPromise>; + usage, TContext = unknown>( + params?: RequestParams.XpackUsage, options?: TransportRequestOptions ): TransportRequestPromise>; }; + /* /GENERATED */ } diff --git a/src/core/server/elasticsearch/client/client_wrapper.ts b/src/core/server/elasticsearch/client/client_wrapper.ts index e270d118a89b4..feda9aea0a76f 100644 --- a/src/core/server/elasticsearch/client/client_wrapper.ts +++ b/src/core/server/elasticsearch/client/client_wrapper.ts @@ -29,23 +29,463 @@ export const getClientFacade = (client: Client, headers: Headers = {}): ClientFa headers, }; } - // TODO: do we need to throw in case of duplicates as it was done - // in legacy? - src/core/server/elasticsearch/scoped_cluster_client.ts:L88 return { ...options, headers: { - ...options.headers, ...headers, + ...options.headers, }, }; }; return { - bulk: (params, options) => client.bulk(params, addHeaders(options)), + /* GENERATED */ asyncSearch: { delete: (params, options) => client.asyncSearch.delete(params, addHeaders(options)), get: (params, options) => client.asyncSearch.get(params, addHeaders(options)), submit: (params, options) => client.asyncSearch.submit(params, addHeaders(options)), }, + autoscaling: { + getAutoscalingDecision: (params, options) => + client.autoscaling.getAutoscalingDecision(params, addHeaders(options)), + }, + bulk: (params, options) => client.bulk(params, addHeaders(options)), + cat: { + aliases: (params, options) => client.cat.aliases(params, addHeaders(options)), + allocation: (params, options) => client.cat.allocation(params, addHeaders(options)), + count: (params, options) => client.cat.count(params, addHeaders(options)), + fielddata: (params, options) => client.cat.fielddata(params, addHeaders(options)), + health: (params, options) => client.cat.health(params, addHeaders(options)), + help: (params, options) => client.cat.help(params, addHeaders(options)), + indices: (params, options) => client.cat.indices(params, addHeaders(options)), + master: (params, options) => client.cat.master(params, addHeaders(options)), + mlDataFrameAnalytics: (params, options) => + client.cat.mlDataFrameAnalytics(params, addHeaders(options)), + mlDatafeeds: (params, options) => client.cat.mlDatafeeds(params, addHeaders(options)), + mlJobs: (params, options) => client.cat.mlJobs(params, addHeaders(options)), + mlTrainedModels: (params, options) => client.cat.mlTrainedModels(params, addHeaders(options)), + nodeattrs: (params, options) => client.cat.nodeattrs(params, addHeaders(options)), + nodes: (params, options) => client.cat.nodes(params, addHeaders(options)), + pendingTasks: (params, options) => client.cat.pendingTasks(params, addHeaders(options)), + plugins: (params, options) => client.cat.plugins(params, addHeaders(options)), + recovery: (params, options) => client.cat.recovery(params, addHeaders(options)), + repositories: (params, options) => client.cat.repositories(params, addHeaders(options)), + segments: (params, options) => client.cat.segments(params, addHeaders(options)), + shards: (params, options) => client.cat.shards(params, addHeaders(options)), + snapshots: (params, options) => client.cat.snapshots(params, addHeaders(options)), + tasks: (params, options) => client.cat.tasks(params, addHeaders(options)), + templates: (params, options) => client.cat.templates(params, addHeaders(options)), + threadPool: (params, options) => client.cat.threadPool(params, addHeaders(options)), + transforms: (params, options) => client.cat.transforms(params, addHeaders(options)), + }, + ccr: { + deleteAutoFollowPattern: (params, options) => + client.ccr.deleteAutoFollowPattern(params, addHeaders(options)), + follow: (params, options) => client.ccr.follow(params, addHeaders(options)), + followInfo: (params, options) => client.ccr.followInfo(params, addHeaders(options)), + followStats: (params, options) => client.ccr.followStats(params, addHeaders(options)), + forgetFollower: (params, options) => client.ccr.forgetFollower(params, addHeaders(options)), + getAutoFollowPattern: (params, options) => + client.ccr.getAutoFollowPattern(params, addHeaders(options)), + pauseAutoFollowPattern: (params, options) => + client.ccr.pauseAutoFollowPattern(params, addHeaders(options)), + pauseFollow: (params, options) => client.ccr.pauseFollow(params, addHeaders(options)), + putAutoFollowPattern: (params, options) => + client.ccr.putAutoFollowPattern(params, addHeaders(options)), + resumeAutoFollowPattern: (params, options) => + client.ccr.resumeAutoFollowPattern(params, addHeaders(options)), + resumeFollow: (params, options) => client.ccr.resumeFollow(params, addHeaders(options)), + stats: (params, options) => client.ccr.stats(params, addHeaders(options)), + unfollow: (params, options) => client.ccr.unfollow(params, addHeaders(options)), + }, + clearScroll: (params, options) => client.clearScroll(params, addHeaders(options)), + cluster: { + allocationExplain: (params, options) => + client.cluster.allocationExplain(params, addHeaders(options)), + deleteComponentTemplate: (params, options) => + client.cluster.deleteComponentTemplate(params, addHeaders(options)), + getComponentTemplate: (params, options) => + client.cluster.getComponentTemplate(params, addHeaders(options)), + getSettings: (params, options) => client.cluster.getSettings(params, addHeaders(options)), + health: (params, options) => client.cluster.health(params, addHeaders(options)), + pendingTasks: (params, options) => client.cluster.pendingTasks(params, addHeaders(options)), + putComponentTemplate: (params, options) => + client.cluster.putComponentTemplate(params, addHeaders(options)), + putSettings: (params, options) => client.cluster.putSettings(params, addHeaders(options)), + remoteInfo: (params, options) => client.cluster.remoteInfo(params, addHeaders(options)), + reroute: (params, options) => client.cluster.reroute(params, addHeaders(options)), + state: (params, options) => client.cluster.state(params, addHeaders(options)), + stats: (params, options) => client.cluster.stats(params, addHeaders(options)), + }, + count: (params, options) => client.count(params, addHeaders(options)), + create: (params, options) => client.create(params, addHeaders(options)), + delete: (params, options) => client.delete(params, addHeaders(options)), + deleteByQuery: (params, options) => client.deleteByQuery(params, addHeaders(options)), + deleteByQueryRethrottle: (params, options) => + client.deleteByQueryRethrottle(params, addHeaders(options)), + deleteScript: (params, options) => client.deleteScript(params, addHeaders(options)), + enrich: { + deletePolicy: (params, options) => client.enrich.deletePolicy(params, addHeaders(options)), + executePolicy: (params, options) => client.enrich.executePolicy(params, addHeaders(options)), + getPolicy: (params, options) => client.enrich.getPolicy(params, addHeaders(options)), + putPolicy: (params, options) => client.enrich.putPolicy(params, addHeaders(options)), + stats: (params, options) => client.enrich.stats(params, addHeaders(options)), + }, + eql: { + search: (params, options) => client.eql.search(params, addHeaders(options)), + }, + exists: (params, options) => client.exists(params, addHeaders(options)), + existsSource: (params, options) => client.existsSource(params, addHeaders(options)), + explain: (params, options) => client.explain(params, addHeaders(options)), + fieldCaps: (params, options) => client.fieldCaps(params, addHeaders(options)), + get: (params, options) => client.get(params, addHeaders(options)), + getScript: (params, options) => client.getScript(params, addHeaders(options)), + getScriptContext: (params, options) => client.getScriptContext(params, addHeaders(options)), + getScriptLanguages: (params, options) => client.getScriptLanguages(params, addHeaders(options)), + getSource: (params, options) => client.getSource(params, addHeaders(options)), + graph: { + explore: (params, options) => client.graph.explore(params, addHeaders(options)), + }, + ilm: { + deleteLifecycle: (params, options) => client.ilm.deleteLifecycle(params, addHeaders(options)), + explainLifecycle: (params, options) => + client.ilm.explainLifecycle(params, addHeaders(options)), + getLifecycle: (params, options) => client.ilm.getLifecycle(params, addHeaders(options)), + getStatus: (params, options) => client.ilm.getStatus(params, addHeaders(options)), + moveToStep: (params, options) => client.ilm.moveToStep(params, addHeaders(options)), + putLifecycle: (params, options) => client.ilm.putLifecycle(params, addHeaders(options)), + removePolicy: (params, options) => client.ilm.removePolicy(params, addHeaders(options)), + retry: (params, options) => client.ilm.retry(params, addHeaders(options)), + start: (params, options) => client.ilm.start(params, addHeaders(options)), + stop: (params, options) => client.ilm.stop(params, addHeaders(options)), + }, + index: (params, options) => client.index(params, addHeaders(options)), + indices: { + analyze: (params, options) => client.indices.analyze(params, addHeaders(options)), + clearCache: (params, options) => client.indices.clearCache(params, addHeaders(options)), + clone: (params, options) => client.indices.clone(params, addHeaders(options)), + close: (params, options) => client.indices.close(params, addHeaders(options)), + create: (params, options) => client.indices.create(params, addHeaders(options)), + createDataStream: (params, options) => + client.indices.createDataStream(params, addHeaders(options)), + delete: (params, options) => client.indices.delete(params, addHeaders(options)), + deleteAlias: (params, options) => client.indices.deleteAlias(params, addHeaders(options)), + deleteDataStream: (params, options) => + client.indices.deleteDataStream(params, addHeaders(options)), + deleteTemplate: (params, options) => + client.indices.deleteTemplate(params, addHeaders(options)), + exists: (params, options) => client.indices.exists(params, addHeaders(options)), + existsAlias: (params, options) => client.indices.existsAlias(params, addHeaders(options)), + existsTemplate: (params, options) => + client.indices.existsTemplate(params, addHeaders(options)), + existsType: (params, options) => client.indices.existsType(params, addHeaders(options)), + flush: (params, options) => client.indices.flush(params, addHeaders(options)), + flushSynced: (params, options) => client.indices.flushSynced(params, addHeaders(options)), + forcemerge: (params, options) => client.indices.forcemerge(params, addHeaders(options)), + freeze: (params, options) => client.indices.freeze(params, addHeaders(options)), + get: (params, options) => client.indices.get(params, addHeaders(options)), + getAlias: (params, options) => client.indices.getAlias(params, addHeaders(options)), + getDataStreams: (params, options) => + client.indices.getDataStreams(params, addHeaders(options)), + getFieldMapping: (params, options) => + client.indices.getFieldMapping(params, addHeaders(options)), + getMapping: (params, options) => client.indices.getMapping(params, addHeaders(options)), + getSettings: (params, options) => client.indices.getSettings(params, addHeaders(options)), + getTemplate: (params, options) => client.indices.getTemplate(params, addHeaders(options)), + getUpgrade: (params, options) => client.indices.getUpgrade(params, addHeaders(options)), + open: (params, options) => client.indices.open(params, addHeaders(options)), + putAlias: (params, options) => client.indices.putAlias(params, addHeaders(options)), + putMapping: (params, options) => client.indices.putMapping(params, addHeaders(options)), + putSettings: (params, options) => client.indices.putSettings(params, addHeaders(options)), + putTemplate: (params, options) => client.indices.putTemplate(params, addHeaders(options)), + recovery: (params, options) => client.indices.recovery(params, addHeaders(options)), + refresh: (params, options) => client.indices.refresh(params, addHeaders(options)), + reloadSearchAnalyzers: (params, options) => + client.indices.reloadSearchAnalyzers(params, addHeaders(options)), + rollover: (params, options) => client.indices.rollover(params, addHeaders(options)), + segments: (params, options) => client.indices.segments(params, addHeaders(options)), + shardStores: (params, options) => client.indices.shardStores(params, addHeaders(options)), + shrink: (params, options) => client.indices.shrink(params, addHeaders(options)), + split: (params, options) => client.indices.split(params, addHeaders(options)), + stats: (params, options) => client.indices.stats(params, addHeaders(options)), + unfreeze: (params, options) => client.indices.unfreeze(params, addHeaders(options)), + updateAliases: (params, options) => client.indices.updateAliases(params, addHeaders(options)), + upgrade: (params, options) => client.indices.upgrade(params, addHeaders(options)), + validateQuery: (params, options) => client.indices.validateQuery(params, addHeaders(options)), + }, + info: (params, options) => client.info(params, addHeaders(options)), + ingest: { + deletePipeline: (params, options) => + client.ingest.deletePipeline(params, addHeaders(options)), + getPipeline: (params, options) => client.ingest.getPipeline(params, addHeaders(options)), + processorGrok: (params, options) => client.ingest.processorGrok(params, addHeaders(options)), + putPipeline: (params, options) => client.ingest.putPipeline(params, addHeaders(options)), + simulate: (params, options) => client.ingest.simulate(params, addHeaders(options)), + }, + license: { + delete: (params, options) => client.license.delete(params, addHeaders(options)), + get: (params, options) => client.license.get(params, addHeaders(options)), + getBasicStatus: (params, options) => + client.license.getBasicStatus(params, addHeaders(options)), + getTrialStatus: (params, options) => + client.license.getTrialStatus(params, addHeaders(options)), + post: (params, options) => client.license.post(params, addHeaders(options)), + postStartBasic: (params, options) => + client.license.postStartBasic(params, addHeaders(options)), + postStartTrial: (params, options) => + client.license.postStartTrial(params, addHeaders(options)), + }, + mget: (params, options) => client.mget(params, addHeaders(options)), + migration: { + deprecations: (params, options) => client.migration.deprecations(params, addHeaders(options)), + }, + ml: { + closeJob: (params, options) => client.ml.closeJob(params, addHeaders(options)), + deleteCalendar: (params, options) => client.ml.deleteCalendar(params, addHeaders(options)), + deleteCalendarEvent: (params, options) => + client.ml.deleteCalendarEvent(params, addHeaders(options)), + deleteCalendarJob: (params, options) => + client.ml.deleteCalendarJob(params, addHeaders(options)), + deleteDataFrameAnalytics: (params, options) => + client.ml.deleteDataFrameAnalytics(params, addHeaders(options)), + deleteDatafeed: (params, options) => client.ml.deleteDatafeed(params, addHeaders(options)), + deleteExpiredData: (params, options) => + client.ml.deleteExpiredData(params, addHeaders(options)), + deleteFilter: (params, options) => client.ml.deleteFilter(params, addHeaders(options)), + deleteForecast: (params, options) => client.ml.deleteForecast(params, addHeaders(options)), + deleteJob: (params, options) => client.ml.deleteJob(params, addHeaders(options)), + deleteModelSnapshot: (params, options) => + client.ml.deleteModelSnapshot(params, addHeaders(options)), + deleteTrainedModel: (params, options) => + client.ml.deleteTrainedModel(params, addHeaders(options)), + estimateModelMemory: (params, options) => + client.ml.estimateModelMemory(params, addHeaders(options)), + evaluateDataFrame: (params, options) => + client.ml.evaluateDataFrame(params, addHeaders(options)), + explainDataFrameAnalytics: (params, options) => + client.ml.explainDataFrameAnalytics(params, addHeaders(options)), + findFileStructure: (params, options) => + client.ml.findFileStructure(params, addHeaders(options)), + flushJob: (params, options) => client.ml.flushJob(params, addHeaders(options)), + forecast: (params, options) => client.ml.forecast(params, addHeaders(options)), + getBuckets: (params, options) => client.ml.getBuckets(params, addHeaders(options)), + getCalendarEvents: (params, options) => + client.ml.getCalendarEvents(params, addHeaders(options)), + getCalendars: (params, options) => client.ml.getCalendars(params, addHeaders(options)), + getCategories: (params, options) => client.ml.getCategories(params, addHeaders(options)), + getDataFrameAnalytics: (params, options) => + client.ml.getDataFrameAnalytics(params, addHeaders(options)), + getDataFrameAnalyticsStats: (params, options) => + client.ml.getDataFrameAnalyticsStats(params, addHeaders(options)), + getDatafeedStats: (params, options) => + client.ml.getDatafeedStats(params, addHeaders(options)), + getDatafeeds: (params, options) => client.ml.getDatafeeds(params, addHeaders(options)), + getFilters: (params, options) => client.ml.getFilters(params, addHeaders(options)), + getInfluencers: (params, options) => client.ml.getInfluencers(params, addHeaders(options)), + getJobStats: (params, options) => client.ml.getJobStats(params, addHeaders(options)), + getJobs: (params, options) => client.ml.getJobs(params, addHeaders(options)), + getModelSnapshots: (params, options) => + client.ml.getModelSnapshots(params, addHeaders(options)), + getOverallBuckets: (params, options) => + client.ml.getOverallBuckets(params, addHeaders(options)), + getRecords: (params, options) => client.ml.getRecords(params, addHeaders(options)), + getTrainedModels: (params, options) => + client.ml.getTrainedModels(params, addHeaders(options)), + getTrainedModelsStats: (params, options) => + client.ml.getTrainedModelsStats(params, addHeaders(options)), + info: (params, options) => client.ml.info(params, addHeaders(options)), + openJob: (params, options) => client.ml.openJob(params, addHeaders(options)), + postCalendarEvents: (params, options) => + client.ml.postCalendarEvents(params, addHeaders(options)), + postData: (params, options) => client.ml.postData(params, addHeaders(options)), + previewDatafeed: (params, options) => client.ml.previewDatafeed(params, addHeaders(options)), + putCalendar: (params, options) => client.ml.putCalendar(params, addHeaders(options)), + putCalendarJob: (params, options) => client.ml.putCalendarJob(params, addHeaders(options)), + putDataFrameAnalytics: (params, options) => + client.ml.putDataFrameAnalytics(params, addHeaders(options)), + putDatafeed: (params, options) => client.ml.putDatafeed(params, addHeaders(options)), + putFilter: (params, options) => client.ml.putFilter(params, addHeaders(options)), + putJob: (params, options) => client.ml.putJob(params, addHeaders(options)), + putTrainedModel: (params, options) => client.ml.putTrainedModel(params, addHeaders(options)), + revertModelSnapshot: (params, options) => + client.ml.revertModelSnapshot(params, addHeaders(options)), + setUpgradeMode: (params, options) => client.ml.setUpgradeMode(params, addHeaders(options)), + startDataFrameAnalytics: (params, options) => + client.ml.startDataFrameAnalytics(params, addHeaders(options)), + startDatafeed: (params, options) => client.ml.startDatafeed(params, addHeaders(options)), + stopDataFrameAnalytics: (params, options) => + client.ml.stopDataFrameAnalytics(params, addHeaders(options)), + stopDatafeed: (params, options) => client.ml.stopDatafeed(params, addHeaders(options)), + updateDatafeed: (params, options) => client.ml.updateDatafeed(params, addHeaders(options)), + updateFilter: (params, options) => client.ml.updateFilter(params, addHeaders(options)), + updateJob: (params, options) => client.ml.updateJob(params, addHeaders(options)), + updateModelSnapshot: (params, options) => + client.ml.updateModelSnapshot(params, addHeaders(options)), + validate: (params, options) => client.ml.validate(params, addHeaders(options)), + validateDetector: (params, options) => + client.ml.validateDetector(params, addHeaders(options)), + }, + monitoring: { + bulk: (params, options) => client.monitoring.bulk(params, addHeaders(options)), + }, + msearch: (params, options) => client.msearch(params, addHeaders(options)), + msearchTemplate: (params, options) => client.msearchTemplate(params, addHeaders(options)), + mtermvectors: (params, options) => client.mtermvectors(params, addHeaders(options)), + nodes: { + hotThreads: (params, options) => client.nodes.hotThreads(params, addHeaders(options)), + info: (params, options) => client.nodes.info(params, addHeaders(options)), + reloadSecureSettings: (params, options) => + client.nodes.reloadSecureSettings(params, addHeaders(options)), + stats: (params, options) => client.nodes.stats(params, addHeaders(options)), + usage: (params, options) => client.nodes.usage(params, addHeaders(options)), + }, + ping: (params, options) => client.ping(params, addHeaders(options)), + putScript: (params, options) => client.putScript(params, addHeaders(options)), + rankEval: (params, options) => client.rankEval(params, addHeaders(options)), + reindex: (params, options) => client.reindex(params, addHeaders(options)), + reindexRethrottle: (params, options) => client.reindexRethrottle(params, addHeaders(options)), + renderSearchTemplate: (params, options) => + client.renderSearchTemplate(params, addHeaders(options)), + rollup: { + deleteJob: (params, options) => client.rollup.deleteJob(params, addHeaders(options)), + getJobs: (params, options) => client.rollup.getJobs(params, addHeaders(options)), + getRollupCaps: (params, options) => client.rollup.getRollupCaps(params, addHeaders(options)), + getRollupIndexCaps: (params, options) => + client.rollup.getRollupIndexCaps(params, addHeaders(options)), + putJob: (params, options) => client.rollup.putJob(params, addHeaders(options)), + rollupSearch: (params, options) => client.rollup.rollupSearch(params, addHeaders(options)), + startJob: (params, options) => client.rollup.startJob(params, addHeaders(options)), + stopJob: (params, options) => client.rollup.stopJob(params, addHeaders(options)), + }, + scriptsPainlessExecute: (params, options) => + client.scriptsPainlessExecute(params, addHeaders(options)), + scroll: (params, options) => client.scroll(params, addHeaders(options)), + search: (params, options) => client.search(params, addHeaders(options)), + searchShards: (params, options) => client.searchShards(params, addHeaders(options)), + searchTemplate: (params, options) => client.searchTemplate(params, addHeaders(options)), + security: { + authenticate: (params, options) => client.security.authenticate(params, addHeaders(options)), + changePassword: (params, options) => + client.security.changePassword(params, addHeaders(options)), + clearCachedRealms: (params, options) => + client.security.clearCachedRealms(params, addHeaders(options)), + clearCachedRoles: (params, options) => + client.security.clearCachedRoles(params, addHeaders(options)), + createApiKey: (params, options) => client.security.createApiKey(params, addHeaders(options)), + deletePrivileges: (params, options) => + client.security.deletePrivileges(params, addHeaders(options)), + deleteRole: (params, options) => client.security.deleteRole(params, addHeaders(options)), + deleteRoleMapping: (params, options) => + client.security.deleteRoleMapping(params, addHeaders(options)), + deleteUser: (params, options) => client.security.deleteUser(params, addHeaders(options)), + disableUser: (params, options) => client.security.disableUser(params, addHeaders(options)), + enableUser: (params, options) => client.security.enableUser(params, addHeaders(options)), + getApiKey: (params, options) => client.security.getApiKey(params, addHeaders(options)), + getBuiltinPrivileges: (params, options) => + client.security.getBuiltinPrivileges(params, addHeaders(options)), + getPrivileges: (params, options) => + client.security.getPrivileges(params, addHeaders(options)), + getRole: (params, options) => client.security.getRole(params, addHeaders(options)), + getRoleMapping: (params, options) => + client.security.getRoleMapping(params, addHeaders(options)), + getToken: (params, options) => client.security.getToken(params, addHeaders(options)), + getUser: (params, options) => client.security.getUser(params, addHeaders(options)), + getUserPrivileges: (params, options) => + client.security.getUserPrivileges(params, addHeaders(options)), + hasPrivileges: (params, options) => + client.security.hasPrivileges(params, addHeaders(options)), + invalidateApiKey: (params, options) => + client.security.invalidateApiKey(params, addHeaders(options)), + invalidateToken: (params, options) => + client.security.invalidateToken(params, addHeaders(options)), + putPrivileges: (params, options) => + client.security.putPrivileges(params, addHeaders(options)), + putRole: (params, options) => client.security.putRole(params, addHeaders(options)), + putRoleMapping: (params, options) => + client.security.putRoleMapping(params, addHeaders(options)), + putUser: (params, options) => client.security.putUser(params, addHeaders(options)), + }, + slm: { + deleteLifecycle: (params, options) => client.slm.deleteLifecycle(params, addHeaders(options)), + executeLifecycle: (params, options) => + client.slm.executeLifecycle(params, addHeaders(options)), + executeRetention: (params, options) => + client.slm.executeRetention(params, addHeaders(options)), + getLifecycle: (params, options) => client.slm.getLifecycle(params, addHeaders(options)), + getStats: (params, options) => client.slm.getStats(params, addHeaders(options)), + getStatus: (params, options) => client.slm.getStatus(params, addHeaders(options)), + putLifecycle: (params, options) => client.slm.putLifecycle(params, addHeaders(options)), + start: (params, options) => client.slm.start(params, addHeaders(options)), + stop: (params, options) => client.slm.stop(params, addHeaders(options)), + }, + snapshot: { + cleanupRepository: (params, options) => + client.snapshot.cleanupRepository(params, addHeaders(options)), + create: (params, options) => client.snapshot.create(params, addHeaders(options)), + createRepository: (params, options) => + client.snapshot.createRepository(params, addHeaders(options)), + delete: (params, options) => client.snapshot.delete(params, addHeaders(options)), + deleteRepository: (params, options) => + client.snapshot.deleteRepository(params, addHeaders(options)), + get: (params, options) => client.snapshot.get(params, addHeaders(options)), + getRepository: (params, options) => + client.snapshot.getRepository(params, addHeaders(options)), + restore: (params, options) => client.snapshot.restore(params, addHeaders(options)), + status: (params, options) => client.snapshot.status(params, addHeaders(options)), + verifyRepository: (params, options) => + client.snapshot.verifyRepository(params, addHeaders(options)), + }, + sql: { + clearCursor: (params, options) => client.sql.clearCursor(params, addHeaders(options)), + query: (params, options) => client.sql.query(params, addHeaders(options)), + translate: (params, options) => client.sql.translate(params, addHeaders(options)), + }, + ssl: { + certificates: (params, options) => client.ssl.certificates(params, addHeaders(options)), + }, + tasks: { + cancel: (params, options) => client.tasks.cancel(params, addHeaders(options)), + get: (params, options) => client.tasks.get(params, addHeaders(options)), + list: (params, options) => client.tasks.list(params, addHeaders(options)), + }, + termvectors: (params, options) => client.termvectors(params, addHeaders(options)), + transform: { + deleteTransform: (params, options) => + client.transform.deleteTransform(params, addHeaders(options)), + getTransform: (params, options) => client.transform.getTransform(params, addHeaders(options)), + getTransformStats: (params, options) => + client.transform.getTransformStats(params, addHeaders(options)), + previewTransform: (params, options) => + client.transform.previewTransform(params, addHeaders(options)), + putTransform: (params, options) => client.transform.putTransform(params, addHeaders(options)), + startTransform: (params, options) => + client.transform.startTransform(params, addHeaders(options)), + stopTransform: (params, options) => + client.transform.stopTransform(params, addHeaders(options)), + updateTransform: (params, options) => + client.transform.updateTransform(params, addHeaders(options)), + }, + update: (params, options) => client.update(params, addHeaders(options)), + updateByQuery: (params, options) => client.updateByQuery(params, addHeaders(options)), + updateByQueryRethrottle: (params, options) => + client.updateByQueryRethrottle(params, addHeaders(options)), + watcher: { + ackWatch: (params, options) => client.watcher.ackWatch(params, addHeaders(options)), + activateWatch: (params, options) => client.watcher.activateWatch(params, addHeaders(options)), + deactivateWatch: (params, options) => + client.watcher.deactivateWatch(params, addHeaders(options)), + deleteWatch: (params, options) => client.watcher.deleteWatch(params, addHeaders(options)), + executeWatch: (params, options) => client.watcher.executeWatch(params, addHeaders(options)), + getWatch: (params, options) => client.watcher.getWatch(params, addHeaders(options)), + putWatch: (params, options) => client.watcher.putWatch(params, addHeaders(options)), + start: (params, options) => client.watcher.start(params, addHeaders(options)), + stats: (params, options) => client.watcher.stats(params, addHeaders(options)), + stop: (params, options) => client.watcher.stop(params, addHeaders(options)), + }, + xpack: { + info: (params, options) => client.xpack.info(params, addHeaders(options)), + usage: (params, options) => client.xpack.usage(params, addHeaders(options)), + }, + /* /GENERATED */ }; }; diff --git a/src/core/server/elasticsearch/client/scoped_cluster_client.ts b/src/core/server/elasticsearch/client/scoped_cluster_client.ts index 7786963aec09e..b64edc8c63f57 100644 --- a/src/core/server/elasticsearch/client/scoped_cluster_client.ts +++ b/src/core/server/elasticsearch/client/scoped_cluster_client.ts @@ -17,7 +17,6 @@ * under the License. */ -import { ClientWrapper } from './client_wrapper'; import { ClientFacade } from './client_facade'; /** @public **/ @@ -29,8 +28,8 @@ export interface IScopedClusterClient { /** @internal **/ export class ScopedClusterClient implements IScopedClusterClient { constructor( - private readonly internalClient: ClientWrapper, - private readonly scopedClient: ClientWrapper + private readonly internalClient: ClientFacade, + private readonly scopedClient: ClientFacade ) {} asInternalUser() { diff --git a/src/dev/generate_es_client.ts b/src/dev/generate_es_client.ts new file mode 100644 index 0000000000000..7da2fea7bc259 --- /dev/null +++ b/src/dev/generate_es_client.ts @@ -0,0 +1,150 @@ +/* + * 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 { resolve, join } from 'path'; +import fs from 'fs'; + +const REPO_ROOT = resolve(__dirname, '../../'); +const GENERATION_START_SYMBOL = '/* GENERATED */'; +const GENERATION_END_SYMBOL = '/* /GENERATED */'; + +const sourceFile = join(REPO_ROOT, 'node_modules', '@elastic', 'elasticsearch', 'index.d.ts'); +const apiFile = join( + REPO_ROOT, + 'src', + 'core', + 'server', + 'elasticsearch', + 'client', + 'client_facade.ts' +); +const implemFile = join( + REPO_ROOT, + 'src', + 'core', + 'server', + 'elasticsearch', + 'client', + 'client_wrapper.ts' +); + +const generate = () => { + const clientAPI = readClientAPI(); + const { api, impl } = processClientAPI(clientAPI); + + writeFacadeAPI(api); + writeWrapperDefinition(impl); + + // apply es-lint to the generated file + // as indentation may not be correct, and some of our lint rules are not respected by the es lib. + process.argv.push('--fix'); + process.argv.push(apiFile); + process.argv.push(implemFile); + require('./run_eslint'); +}; + +const apiLineRegexp = /^([a-zA-Z_]*)[<]/; +const callbackApiRegexp = /TransportRequestCallback/; + +const blockStartRegexp = /^([a-zA-Z_]*)[:][ ][{]$/; +const blockEndRegexp = /^[}]$/; + +const processClientAPI = (rawContent: string) => { + const apiLines: string[] = []; + const implementationLines: string[] = []; + + let currentBlock: string | null = null; + let inDeletedBlock = false; + + rawContent + .split('\n') + .map((line) => line.trim()) + .forEach((line) => { + const blockStartMatch = blockStartRegexp.exec(line); + + // start of a block of API, I.E : `asyncSearch: {` + if (blockStartMatch) { + currentBlock = blockStartMatch[1]; + if (currentBlock.includes('_')) { + inDeletedBlock = true; + } else { + // add `[blockName]: {` to both API and implementation + apiLines.push(line); + implementationLines.push(line); + } + } else if (blockEndRegexp.test(line)) { + if (!inDeletedBlock) { + apiLines.push('}'); + implementationLines.push('},'); + } + currentBlock = null; + inDeletedBlock = false; + } else { + const isApiLineMatch = apiLineRegexp.exec(line); + const isCallbackApi = callbackApiRegexp.test(line); + if (isApiLineMatch && !isCallbackApi && !inDeletedBlock) { + const apiName = isApiLineMatch[1]; + if (!apiName.includes('_')) { + apiLines.push(line); + implementationLines.push( + `${apiName}: (params, options) => client${ + currentBlock ? '.' + currentBlock : '' + }.${apiName}(params, addHeaders(options)),` + ); + } + } + } + }); + + return { api: apiLines.join('\n'), impl: implementationLines.join('\n') }; +}; + +const readClientAPI = (): string => { + const sourceFileContent = fs.readFileSync(sourceFile).toString('utf-8'); + return sourceFileContent.substring( + sourceFileContent.indexOf(GENERATION_START_SYMBOL) + GENERATION_START_SYMBOL.length, + sourceFileContent.indexOf(GENERATION_END_SYMBOL) + ); +}; + +const writeFacadeAPI = (apiDefinition: string) => { + injectGeneratedContent(apiFile, apiDefinition); +}; + +const writeWrapperDefinition = (implemDefinition: string) => { + injectGeneratedContent(implemFile, implemDefinition); +}; + +const injectGeneratedContent = (filepath: string, injectedContent: string) => { + const fileContent = fs.readFileSync(filepath, 'utf-8').toString(); + + const newFileContent = + fileContent.slice( + 0, + fileContent.indexOf(GENERATION_START_SYMBOL) + GENERATION_START_SYMBOL.length + ) + + `\n` + + injectedContent + + `\n` + + fileContent.slice(fileContent.indexOf(GENERATION_END_SYMBOL)); + + fs.writeFileSync(filepath, newFileContent); +}; + +generate(); From 024f3dfd3d719f0692da260ab9c63298e8df871c Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 08:41:09 +0200 Subject: [PATCH 05/42] add back keepAlive --- src/core/server/elasticsearch/client/client_config.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/core/server/elasticsearch/client/client_config.ts b/src/core/server/elasticsearch/client/client_config.ts index 64a9234778b83..bb59b89ac9300 100644 --- a/src/core/server/elasticsearch/client/client_config.ts +++ b/src/core/server/elasticsearch/client/client_config.ts @@ -45,6 +45,7 @@ export type ElasticsearchClientConfig = Pick< pingTimeout?: ElasticsearchConfig['pingTimeout'] | ClientOptions['pingTimeout']; requestTimeout?: ElasticsearchConfig['requestTimeout'] | ClientOptions['requestTimeout']; ssl?: Partial; + keepAlive?: boolean; }; export function parseClientOptions( @@ -66,6 +67,11 @@ export function parseClientOptions( if (config.sniffInterval) { clientOptions.sniffInterval = getDurationAsMs(config.sniffInterval); } + if (config.keepAlive) { + clientOptions.agent = { + keepAlive: config.keepAlive, + }; + } // TODO: this can either be done globally here or by host in convertHost. // Not sure which option is the best. From eecd780a3acd05b6cac0baa66b32390c2e266ef7 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 09:38:01 +0200 Subject: [PATCH 06/42] add exports from client --- .../elasticsearch/client/cluster_client.ts | 15 +++---- ...client_wrapper.ts => get_client_facade.ts} | 8 ++++ src/core/server/elasticsearch/client/index.ts | 6 +++ src/core/server/elasticsearch/client/types.ts | 39 ------------------- 4 files changed, 22 insertions(+), 46 deletions(-) rename src/core/server/elasticsearch/client/{client_wrapper.ts => get_client_facade.ts} (99%) delete mode 100644 src/core/server/elasticsearch/client/types.ts diff --git a/src/core/server/elasticsearch/client/cluster_client.ts b/src/core/server/elasticsearch/client/cluster_client.ts index c52b41072c473..111cd2346354a 100644 --- a/src/core/server/elasticsearch/client/cluster_client.ts +++ b/src/core/server/elasticsearch/client/cluster_client.ts @@ -18,24 +18,25 @@ */ import { Client } from '@elastic/elasticsearch'; -import { getClientFacade } from './client_wrapper'; +import { Logger } from '../../logging'; +import { GetAuthHeaders, isRealRequest, Headers } from '../../http'; +import { ensureRawRequest, filterHeaders } from '../../http/router'; +import { ScopeableRequest } from '../types'; +import { getClientFacade } from './get_client_facade'; import { ClientFacade } from './client_facade'; import { configureClient } from './configure_client'; -import { Logger } from '../../logging'; -import { GetAuthHeaders, isRealRequest } from '../../http'; -import { Headers } from '../../http/router'; import { ElasticsearchClientConfig } from './client_config'; import { ScopedClusterClient, IScopedClusterClient } from './scoped_cluster_client'; -import { ScopeableRequest } from './types'; -import { ensureRawRequest, filterHeaders } from '../../http/router'; const noop = () => undefined; -interface IClusterClient { +/** @public **/ +export interface IClusterClient { asInternalUser: () => ClientFacade; asScoped: (request: ScopeableRequest) => IScopedClusterClient; } +/** @internal **/ export class ClusterClient implements IClusterClient { private readonly internalWrapper: ClientFacade; private readonly scopedClient: Client; diff --git a/src/core/server/elasticsearch/client/client_wrapper.ts b/src/core/server/elasticsearch/client/get_client_facade.ts similarity index 99% rename from src/core/server/elasticsearch/client/client_wrapper.ts rename to src/core/server/elasticsearch/client/get_client_facade.ts index feda9aea0a76f..65d872d7484e9 100644 --- a/src/core/server/elasticsearch/client/client_wrapper.ts +++ b/src/core/server/elasticsearch/client/get_client_facade.ts @@ -22,6 +22,14 @@ import { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport'; import { Headers } from '../../http/router'; import { ClientFacade } from './client_facade'; +/** + * Returns a {@link ClientFacade | facade} to be used to query given es client. + * + * This is used both for the internal client and the scoped ones. authorization header + * must be passed when creating a scoped facade. + * + * @internal + */ export const getClientFacade = (client: Client, headers: Headers = {}): ClientFacade => { const addHeaders = (options?: TransportRequestOptions): TransportRequestOptions => { if (!options) { diff --git a/src/core/server/elasticsearch/client/index.ts b/src/core/server/elasticsearch/client/index.ts index 9880b336e76e5..971283ed498d4 100644 --- a/src/core/server/elasticsearch/client/index.ts +++ b/src/core/server/elasticsearch/client/index.ts @@ -16,3 +16,9 @@ * specific language governing permissions and limitations * under the License. */ + +export { IScopedClusterClient, ScopedClusterClient } from './scoped_cluster_client'; +export { ClientFacade } from './client_facade'; +export { ElasticsearchClientConfig } from './client_config'; +export { IClusterClient, ClusterClient } from './cluster_client'; +export { configureClient } from './configure_client'; diff --git a/src/core/server/elasticsearch/client/types.ts b/src/core/server/elasticsearch/client/types.ts deleted file mode 100644 index 38e6acbb9323d..0000000000000 --- a/src/core/server/elasticsearch/client/types.ts +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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 { LegacyRequest } from '../../http'; -import { Headers, KibanaRequest } from '../../http/router'; - -/** - * Fake request object created manually by Kibana plugins. - * @public - */ -export interface FakeRequest { - /** Headers used for authentication against Elasticsearch */ - headers: Headers; -} - -/** - A user credentials container. - * It accommodates the necessary auth credentials to impersonate the current user. - * - * @public - * See {@link KibanaRequest}. - */ -export type ScopeableRequest = KibanaRequest | LegacyRequest | FakeRequest; From 8c6c9fc93898b168dcc574f9689f5c66d4246dee Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 10:29:51 +0200 Subject: [PATCH 07/42] add new client mocks --- .../client/client_facade.mock.ts | 395 ++++++++++++++++++ src/core/server/elasticsearch/client/mocks.ts | 52 +++ src/dev/generate_es_client.ts | 41 +- 3 files changed, 468 insertions(+), 20 deletions(-) create mode 100644 src/core/server/elasticsearch/client/client_facade.mock.ts create mode 100644 src/core/server/elasticsearch/client/mocks.ts diff --git a/src/core/server/elasticsearch/client/client_facade.mock.ts b/src/core/server/elasticsearch/client/client_facade.mock.ts new file mode 100644 index 0000000000000..3cbaacdef34a9 --- /dev/null +++ b/src/core/server/elasticsearch/client/client_facade.mock.ts @@ -0,0 +1,395 @@ +/* + * 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 { ClientFacade } from './client_facade'; + +const createFacadeMock = (): jest.Mocked => { + const mock: jest.Mocked = { + /* GENERATED */ + asyncSearch: { + delete: jest.fn(), + get: jest.fn(), + submit: jest.fn(), + }, + autoscaling: { + getAutoscalingDecision: jest.fn(), + }, + bulk: jest.fn(), + cat: { + aliases: jest.fn(), + allocation: jest.fn(), + count: jest.fn(), + fielddata: jest.fn(), + health: jest.fn(), + help: jest.fn(), + indices: jest.fn(), + master: jest.fn(), + mlDataFrameAnalytics: jest.fn(), + mlDatafeeds: jest.fn(), + mlJobs: jest.fn(), + mlTrainedModels: jest.fn(), + nodeattrs: jest.fn(), + nodes: jest.fn(), + pendingTasks: jest.fn(), + plugins: jest.fn(), + recovery: jest.fn(), + repositories: jest.fn(), + segments: jest.fn(), + shards: jest.fn(), + snapshots: jest.fn(), + tasks: jest.fn(), + templates: jest.fn(), + threadPool: jest.fn(), + transforms: jest.fn(), + }, + ccr: { + deleteAutoFollowPattern: jest.fn(), + follow: jest.fn(), + followInfo: jest.fn(), + followStats: jest.fn(), + forgetFollower: jest.fn(), + getAutoFollowPattern: jest.fn(), + pauseAutoFollowPattern: jest.fn(), + pauseFollow: jest.fn(), + putAutoFollowPattern: jest.fn(), + resumeAutoFollowPattern: jest.fn(), + resumeFollow: jest.fn(), + stats: jest.fn(), + unfollow: jest.fn(), + }, + clearScroll: jest.fn(), + cluster: { + allocationExplain: jest.fn(), + deleteComponentTemplate: jest.fn(), + getComponentTemplate: jest.fn(), + getSettings: jest.fn(), + health: jest.fn(), + pendingTasks: jest.fn(), + putComponentTemplate: jest.fn(), + putSettings: jest.fn(), + remoteInfo: jest.fn(), + reroute: jest.fn(), + state: jest.fn(), + stats: jest.fn(), + }, + count: jest.fn(), + create: jest.fn(), + delete: jest.fn(), + deleteByQuery: jest.fn(), + deleteByQueryRethrottle: jest.fn(), + deleteScript: jest.fn(), + enrich: { + deletePolicy: jest.fn(), + executePolicy: jest.fn(), + getPolicy: jest.fn(), + putPolicy: jest.fn(), + stats: jest.fn(), + }, + eql: { + search: jest.fn(), + }, + exists: jest.fn(), + existsSource: jest.fn(), + explain: jest.fn(), + fieldCaps: jest.fn(), + get: jest.fn(), + getScript: jest.fn(), + getScriptContext: jest.fn(), + getScriptLanguages: jest.fn(), + getSource: jest.fn(), + graph: { + explore: jest.fn(), + }, + ilm: { + deleteLifecycle: jest.fn(), + explainLifecycle: jest.fn(), + getLifecycle: jest.fn(), + getStatus: jest.fn(), + moveToStep: jest.fn(), + putLifecycle: jest.fn(), + removePolicy: jest.fn(), + retry: jest.fn(), + start: jest.fn(), + stop: jest.fn(), + }, + index: jest.fn(), + indices: { + analyze: jest.fn(), + clearCache: jest.fn(), + clone: jest.fn(), + close: jest.fn(), + create: jest.fn(), + createDataStream: jest.fn(), + delete: jest.fn(), + deleteAlias: jest.fn(), + deleteDataStream: jest.fn(), + deleteTemplate: jest.fn(), + exists: jest.fn(), + existsAlias: jest.fn(), + existsTemplate: jest.fn(), + existsType: jest.fn(), + flush: jest.fn(), + flushSynced: jest.fn(), + forcemerge: jest.fn(), + freeze: jest.fn(), + get: jest.fn(), + getAlias: jest.fn(), + getDataStreams: jest.fn(), + getFieldMapping: jest.fn(), + getMapping: jest.fn(), + getSettings: jest.fn(), + getTemplate: jest.fn(), + getUpgrade: jest.fn(), + open: jest.fn(), + putAlias: jest.fn(), + putMapping: jest.fn(), + putSettings: jest.fn(), + putTemplate: jest.fn(), + recovery: jest.fn(), + refresh: jest.fn(), + reloadSearchAnalyzers: jest.fn(), + rollover: jest.fn(), + segments: jest.fn(), + shardStores: jest.fn(), + shrink: jest.fn(), + split: jest.fn(), + stats: jest.fn(), + unfreeze: jest.fn(), + updateAliases: jest.fn(), + upgrade: jest.fn(), + validateQuery: jest.fn(), + }, + info: jest.fn(), + ingest: { + deletePipeline: jest.fn(), + getPipeline: jest.fn(), + processorGrok: jest.fn(), + putPipeline: jest.fn(), + simulate: jest.fn(), + }, + license: { + delete: jest.fn(), + get: jest.fn(), + getBasicStatus: jest.fn(), + getTrialStatus: jest.fn(), + post: jest.fn(), + postStartBasic: jest.fn(), + postStartTrial: jest.fn(), + }, + mget: jest.fn(), + migration: { + deprecations: jest.fn(), + }, + ml: { + closeJob: jest.fn(), + deleteCalendar: jest.fn(), + deleteCalendarEvent: jest.fn(), + deleteCalendarJob: jest.fn(), + deleteDataFrameAnalytics: jest.fn(), + deleteDatafeed: jest.fn(), + deleteExpiredData: jest.fn(), + deleteFilter: jest.fn(), + deleteForecast: jest.fn(), + deleteJob: jest.fn(), + deleteModelSnapshot: jest.fn(), + deleteTrainedModel: jest.fn(), + estimateModelMemory: jest.fn(), + evaluateDataFrame: jest.fn(), + explainDataFrameAnalytics: jest.fn(), + findFileStructure: jest.fn(), + flushJob: jest.fn(), + forecast: jest.fn(), + getBuckets: jest.fn(), + getCalendarEvents: jest.fn(), + getCalendars: jest.fn(), + getCategories: jest.fn(), + getDataFrameAnalytics: jest.fn(), + getDataFrameAnalyticsStats: jest.fn(), + getDatafeedStats: jest.fn(), + getDatafeeds: jest.fn(), + getFilters: jest.fn(), + getInfluencers: jest.fn(), + getJobStats: jest.fn(), + getJobs: jest.fn(), + getModelSnapshots: jest.fn(), + getOverallBuckets: jest.fn(), + getRecords: jest.fn(), + getTrainedModels: jest.fn(), + getTrainedModelsStats: jest.fn(), + info: jest.fn(), + openJob: jest.fn(), + postCalendarEvents: jest.fn(), + postData: jest.fn(), + previewDatafeed: jest.fn(), + putCalendar: jest.fn(), + putCalendarJob: jest.fn(), + putDataFrameAnalytics: jest.fn(), + putDatafeed: jest.fn(), + putFilter: jest.fn(), + putJob: jest.fn(), + putTrainedModel: jest.fn(), + revertModelSnapshot: jest.fn(), + setUpgradeMode: jest.fn(), + startDataFrameAnalytics: jest.fn(), + startDatafeed: jest.fn(), + stopDataFrameAnalytics: jest.fn(), + stopDatafeed: jest.fn(), + updateDatafeed: jest.fn(), + updateFilter: jest.fn(), + updateJob: jest.fn(), + updateModelSnapshot: jest.fn(), + validate: jest.fn(), + validateDetector: jest.fn(), + }, + monitoring: { + bulk: jest.fn(), + }, + msearch: jest.fn(), + msearchTemplate: jest.fn(), + mtermvectors: jest.fn(), + nodes: { + hotThreads: jest.fn(), + info: jest.fn(), + reloadSecureSettings: jest.fn(), + stats: jest.fn(), + usage: jest.fn(), + }, + ping: jest.fn(), + putScript: jest.fn(), + rankEval: jest.fn(), + reindex: jest.fn(), + reindexRethrottle: jest.fn(), + renderSearchTemplate: jest.fn(), + rollup: { + deleteJob: jest.fn(), + getJobs: jest.fn(), + getRollupCaps: jest.fn(), + getRollupIndexCaps: jest.fn(), + putJob: jest.fn(), + rollupSearch: jest.fn(), + startJob: jest.fn(), + stopJob: jest.fn(), + }, + scriptsPainlessExecute: jest.fn(), + scroll: jest.fn(), + search: jest.fn(), + searchShards: jest.fn(), + searchTemplate: jest.fn(), + security: { + authenticate: jest.fn(), + changePassword: jest.fn(), + clearCachedRealms: jest.fn(), + clearCachedRoles: jest.fn(), + createApiKey: jest.fn(), + deletePrivileges: jest.fn(), + deleteRole: jest.fn(), + deleteRoleMapping: jest.fn(), + deleteUser: jest.fn(), + disableUser: jest.fn(), + enableUser: jest.fn(), + getApiKey: jest.fn(), + getBuiltinPrivileges: jest.fn(), + getPrivileges: jest.fn(), + getRole: jest.fn(), + getRoleMapping: jest.fn(), + getToken: jest.fn(), + getUser: jest.fn(), + getUserPrivileges: jest.fn(), + hasPrivileges: jest.fn(), + invalidateApiKey: jest.fn(), + invalidateToken: jest.fn(), + putPrivileges: jest.fn(), + putRole: jest.fn(), + putRoleMapping: jest.fn(), + putUser: jest.fn(), + }, + slm: { + deleteLifecycle: jest.fn(), + executeLifecycle: jest.fn(), + executeRetention: jest.fn(), + getLifecycle: jest.fn(), + getStats: jest.fn(), + getStatus: jest.fn(), + putLifecycle: jest.fn(), + start: jest.fn(), + stop: jest.fn(), + }, + snapshot: { + cleanupRepository: jest.fn(), + create: jest.fn(), + createRepository: jest.fn(), + delete: jest.fn(), + deleteRepository: jest.fn(), + get: jest.fn(), + getRepository: jest.fn(), + restore: jest.fn(), + status: jest.fn(), + verifyRepository: jest.fn(), + }, + sql: { + clearCursor: jest.fn(), + query: jest.fn(), + translate: jest.fn(), + }, + ssl: { + certificates: jest.fn(), + }, + tasks: { + cancel: jest.fn(), + get: jest.fn(), + list: jest.fn(), + }, + termvectors: jest.fn(), + transform: { + deleteTransform: jest.fn(), + getTransform: jest.fn(), + getTransformStats: jest.fn(), + previewTransform: jest.fn(), + putTransform: jest.fn(), + startTransform: jest.fn(), + stopTransform: jest.fn(), + updateTransform: jest.fn(), + }, + update: jest.fn(), + updateByQuery: jest.fn(), + updateByQueryRethrottle: jest.fn(), + watcher: { + ackWatch: jest.fn(), + activateWatch: jest.fn(), + deactivateWatch: jest.fn(), + deleteWatch: jest.fn(), + executeWatch: jest.fn(), + getWatch: jest.fn(), + putWatch: jest.fn(), + start: jest.fn(), + stats: jest.fn(), + stop: jest.fn(), + }, + xpack: { + info: jest.fn(), + usage: jest.fn(), + }, + /* /GENERATED */ + }; + return mock; +}; + +export const clientFacadeMock = { + create: createFacadeMock, +}; diff --git a/src/core/server/elasticsearch/client/mocks.ts b/src/core/server/elasticsearch/client/mocks.ts new file mode 100644 index 0000000000000..9025ca815b140 --- /dev/null +++ b/src/core/server/elasticsearch/client/mocks.ts @@ -0,0 +1,52 @@ +/* + * 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 { clientFacadeMock } from './client_facade.mock'; +import { IScopedClusterClient } from './scoped_cluster_client'; +import { IClusterClient } from './cluster_client'; + +const createScopedClusterClientMock = () => { + const mock: jest.Mocked = { + asInternalUser: jest.fn(), + asCurrentUser: jest.fn(), + }; + + mock.asInternalUser.mockReturnValue(clientFacadeMock.create()); + mock.asCurrentUser.mockReturnValue(clientFacadeMock.create()); + + return mock; +}; + +const createClusterClientMock = () => { + const mock: jest.Mocked = { + asInternalUser: jest.fn(), + asScoped: jest.fn(), + }; + + mock.asInternalUser.mockReturnValue(clientFacadeMock.create()); + mock.asScoped.mockReturnValue(createScopedClusterClientMock()); + + return mock; +}; + +export const clientMock = { + createClusterClient: createClusterClientMock, + createScopedClusterClient: createScopedClusterClientMock, + createFacade: clientFacadeMock.create, +}; diff --git a/src/dev/generate_es_client.ts b/src/dev/generate_es_client.ts index 7da2fea7bc259..55a403d820d8b 100644 --- a/src/dev/generate_es_client.ts +++ b/src/dev/generate_es_client.ts @@ -25,37 +25,26 @@ const GENERATION_START_SYMBOL = '/* GENERATED */'; const GENERATION_END_SYMBOL = '/* /GENERATED */'; const sourceFile = join(REPO_ROOT, 'node_modules', '@elastic', 'elasticsearch', 'index.d.ts'); -const apiFile = join( - REPO_ROOT, - 'src', - 'core', - 'server', - 'elasticsearch', - 'client', - 'client_facade.ts' -); -const implemFile = join( - REPO_ROOT, - 'src', - 'core', - 'server', - 'elasticsearch', - 'client', - 'client_wrapper.ts' -); + +const targetFolder = join(REPO_ROOT, 'src', 'core', 'server', 'elasticsearch', 'client'); +const apiFile = join(targetFolder, 'client_facade.ts'); +const implemFile = join(targetFolder, 'get_client_facade.ts'); +const mockFile = join(targetFolder, 'client_facade.mock.ts'); const generate = () => { const clientAPI = readClientAPI(); - const { api, impl } = processClientAPI(clientAPI); + const { api, impl, mock } = processClientAPI(clientAPI); writeFacadeAPI(api); writeWrapperDefinition(impl); + writeMockDefinition(mock); // apply es-lint to the generated file // as indentation may not be correct, and some of our lint rules are not respected by the es lib. process.argv.push('--fix'); process.argv.push(apiFile); process.argv.push(implemFile); + process.argv.push(mockFile); require('./run_eslint'); }; @@ -68,6 +57,7 @@ const blockEndRegexp = /^[}]$/; const processClientAPI = (rawContent: string) => { const apiLines: string[] = []; const implementationLines: string[] = []; + const mockLines: string[] = []; let currentBlock: string | null = null; let inDeletedBlock = false; @@ -87,11 +77,13 @@ const processClientAPI = (rawContent: string) => { // add `[blockName]: {` to both API and implementation apiLines.push(line); implementationLines.push(line); + mockLines.push(line); } } else if (blockEndRegexp.test(line)) { if (!inDeletedBlock) { apiLines.push('}'); implementationLines.push('},'); + mockLines.push('},'); } currentBlock = null; inDeletedBlock = false; @@ -107,12 +99,17 @@ const processClientAPI = (rawContent: string) => { currentBlock ? '.' + currentBlock : '' }.${apiName}(params, addHeaders(options)),` ); + mockLines.push(`${apiName}: jest.fn(),`); } } } }); - return { api: apiLines.join('\n'), impl: implementationLines.join('\n') }; + return { + api: apiLines.join('\n'), + impl: implementationLines.join('\n'), + mock: mockLines.join('\n'), + }; }; const readClientAPI = (): string => { @@ -131,6 +128,10 @@ const writeWrapperDefinition = (implemDefinition: string) => { injectGeneratedContent(implemFile, implemDefinition); }; +const writeMockDefinition = (mockDefinition: string) => { + injectGeneratedContent(mockFile, mockDefinition); +}; + const injectGeneratedContent = (filepath: string, injectedContent: string) => { const fileContent = fs.readFileSync(filepath, 'utf-8').toString(); From c7a2cf11496ef87a577768973969f9147647af2e Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 10:48:05 +0200 Subject: [PATCH 08/42] add some doc --- .../elasticsearch/client/cluster_client.ts | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/core/server/elasticsearch/client/cluster_client.ts b/src/core/server/elasticsearch/client/cluster_client.ts index 111cd2346354a..461a3e6ce264a 100644 --- a/src/core/server/elasticsearch/client/cluster_client.ts +++ b/src/core/server/elasticsearch/client/cluster_client.ts @@ -30,15 +30,27 @@ import { ScopedClusterClient, IScopedClusterClient } from './scoped_cluster_clie const noop = () => undefined; -/** @public **/ +/** + * Represents an Elasticsearch cluster API client created by the platform. + * It allows to call API on behalf of the internal Kibana user and + * the actual user that is derived from the request headers (via `asScoped(...)`). + * + * @public + **/ export interface IClusterClient { + /** + * Returns a {@link ClientFacade | facade} to be used to query the ES cluster on behalf of the Kibana internal user + */ asInternalUser: () => ClientFacade; + /** + * Creates a {@link IScopedClusterClient | scoped cluster client} bound to given {@link ScopeableRequest | request} + */ asScoped: (request: ScopeableRequest) => IScopedClusterClient; } /** @internal **/ export class ClusterClient implements IClusterClient { - private readonly internalWrapper: ClientFacade; + private readonly internalFacade: ClientFacade; private readonly scopedClient: Client; constructor( @@ -46,18 +58,18 @@ export class ClusterClient implements IClusterClient { logger: Logger, private readonly getAuthHeaders: GetAuthHeaders = noop ) { - this.internalWrapper = getClientFacade(configureClient(config, { logger })); + this.internalFacade = getClientFacade(configureClient(config, { logger })); this.scopedClient = configureClient(config, { logger, scoped: true }); } asInternalUser() { - return this.internalWrapper; + return this.internalFacade; } asScoped(request: ScopeableRequest) { const headers = this.getScopedHeaders(request); const scopedWrapper = getClientFacade(this.scopedClient, headers); - return new ScopedClusterClient(this.internalWrapper, scopedWrapper); + return new ScopedClusterClient(this.internalFacade, scopedWrapper); } private getScopedHeaders(request: ScopeableRequest): Headers { From 193fecc80d51e917c8cedb163d09e307e14ed5ad Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 11:07:39 +0200 Subject: [PATCH 09/42] fix API usages --- x-pack/test/api_integration/apis/fleet/agents/acks.ts | 2 +- x-pack/test/api_integration/apis/fleet/agents/checkin.ts | 2 +- x-pack/test/api_integration/apis/fleet/agents/enroll.ts | 2 +- .../upgrade_assistant_integration/upgrade_assistant/status.ts | 3 ++- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/x-pack/test/api_integration/apis/fleet/agents/acks.ts b/x-pack/test/api_integration/apis/fleet/agents/acks.ts index 45833012cb475..e8381aa9d59ea 100644 --- a/x-pack/test/api_integration/apis/fleet/agents/acks.ts +++ b/x-pack/test/api_integration/apis/fleet/agents/acks.ts @@ -22,7 +22,7 @@ export default function (providerContext: FtrProviderContext) { before(async () => { await esArchiver.loadIfNeeded('fleet/agents'); - const { body: apiKeyBody } = await esClient.security.createApiKey({ + const { body: apiKeyBody } = await esClient.security.createApiKey({ body: { name: `test access api key: ${uuid.v4()}`, }, diff --git a/x-pack/test/api_integration/apis/fleet/agents/checkin.ts b/x-pack/test/api_integration/apis/fleet/agents/checkin.ts index d24f7f495a06c..8942deafdd83c 100644 --- a/x-pack/test/api_integration/apis/fleet/agents/checkin.ts +++ b/x-pack/test/api_integration/apis/fleet/agents/checkin.ts @@ -22,7 +22,7 @@ export default function (providerContext: FtrProviderContext) { before(async () => { await esArchiver.loadIfNeeded('fleet/agents'); - const { body: apiKeyBody } = await esClient.security.createApiKey({ + const { body: apiKeyBody } = await esClient.security.createApiKey({ body: { name: `test access api key: ${uuid.v4()}`, }, diff --git a/x-pack/test/api_integration/apis/fleet/agents/enroll.ts b/x-pack/test/api_integration/apis/fleet/agents/enroll.ts index ca9a0d57a3ea6..71f9df188179c 100644 --- a/x-pack/test/api_integration/apis/fleet/agents/enroll.ts +++ b/x-pack/test/api_integration/apis/fleet/agents/enroll.ts @@ -23,7 +23,7 @@ export default function (providerContext: FtrProviderContext) { before(async () => { await esArchiver.loadIfNeeded('fleet/agents'); - const { body: apiKeyBody } = await esClient.security.createApiKey({ + const { body: apiKeyBody } = await esClient.security.createApiKey({ body: { name: `test access api key: ${uuid.v4()}`, }, diff --git a/x-pack/test/upgrade_assistant_integration/upgrade_assistant/status.ts b/x-pack/test/upgrade_assistant_integration/upgrade_assistant/status.ts index 76cea64bffc1c..d13b9836f25a1 100644 --- a/x-pack/test/upgrade_assistant_integration/upgrade_assistant/status.ts +++ b/x-pack/test/upgrade_assistant_integration/upgrade_assistant/status.ts @@ -6,6 +6,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../api_integration/ftr_provider_context'; +import { ClusterStateAPIResponse } from '../../../plugins/upgrade_assistant/common/types'; import { getIndexStateFromClusterState } from '../../../plugins/upgrade_assistant/common/get_index_state_from_cluster_state'; // eslint-disable-next-line import/no-default-export @@ -28,7 +29,7 @@ export default function ({ getService }: FtrProviderContext) { it('the _cluster/state endpoint is still what we expect', async () => { await esArchiver.load('upgrade_assistant/reindex'); await es.indices.close({ index: '7.0-data' }); - const result = await es.cluster.state({ + const result = await es.cluster.state({ index: '7.0-data', metric: 'metadata', }); From b8935d7c0929e7c0f489ab26a649c1ad71b68ece Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 11:45:53 +0200 Subject: [PATCH 10/42] rename legacy client to legacy in service --- .../elasticsearch/client/cluster_client.ts | 22 ++++++++- .../elasticsearch/elasticsearch_service.ts | 47 +++++++++++-------- 2 files changed, 47 insertions(+), 22 deletions(-) diff --git a/src/core/server/elasticsearch/client/cluster_client.ts b/src/core/server/elasticsearch/client/cluster_client.ts index 461a3e6ce264a..8106dca69cd6e 100644 --- a/src/core/server/elasticsearch/client/cluster_client.ts +++ b/src/core/server/elasticsearch/client/cluster_client.ts @@ -50,15 +50,19 @@ export interface IClusterClient { /** @internal **/ export class ClusterClient implements IClusterClient { - private readonly internalFacade: ClientFacade; + private readonly internalClient: Client; private readonly scopedClient: Client; + private readonly internalFacade: ClientFacade; + private isClosed = false; + constructor( private readonly config: ElasticsearchClientConfig, logger: Logger, private readonly getAuthHeaders: GetAuthHeaders = noop ) { - this.internalFacade = getClientFacade(configureClient(config, { logger })); + this.internalClient = configureClient(config, { logger }); + this.internalFacade = getClientFacade(this.internalClient); this.scopedClient = configureClient(config, { logger, scoped: true }); } @@ -72,6 +76,20 @@ export class ClusterClient implements IClusterClient { return new ScopedClusterClient(this.internalFacade, scopedWrapper); } + /** + * Closes the cluster client. After that client cannot be used and one should + * create a new client instance to be able to interact with Elasticsearch API. + */ + public close() { + if (this.isClosed) { + return; + } + + this.isClosed = true; + this.internalClient.close(); + this.scopedClient.close(); + } + private getScopedHeaders(request: ScopeableRequest): Headers { if (!isRealRequest(request)) { return request?.headers ?? {}; diff --git a/src/core/server/elasticsearch/elasticsearch_service.ts b/src/core/server/elasticsearch/elasticsearch_service.ts index f47b33dd410f6..d487d766efd59 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.ts @@ -53,7 +53,7 @@ import { calculateStatus$ } from './status'; /** @internal */ interface CoreClusterClients { config: ElasticsearchConfig; - client: LegacyClusterClient; + legacyClient: LegacyClusterClient; } interface SetupDeps { @@ -68,11 +68,11 @@ export class ElasticsearchService private subscription?: Subscription; private stop$ = new Subject(); private kibanaVersion: string; - private createClient?: ( + private createLegacyClient?: ( type: string, clientConfig?: Partial ) => ILegacyCustomClusterClient; - private client?: ILegacyClusterClient; + private legacyClient?: ILegacyClusterClient; constructor(private readonly coreContext: CoreContext) { this.kibanaVersion = coreContext.env.packageInfo.version; @@ -101,7 +101,11 @@ export class ElasticsearchService const coreClients = { config, - client: this.createClusterClient('data', config, deps.http.getAuthHeaders), + legacyClient: this.createLegacyClusterClient( + 'data', + config, + deps.http.getAuthHeaders + ), }; subscriber.next(coreClients); @@ -109,7 +113,7 @@ export class ElasticsearchService return () => { this.log.debug('Closing elasticsearch client'); - coreClients.client.close(); + coreClients.legacyClient.close(); }; }) ), @@ -120,26 +124,26 @@ export class ElasticsearchService const config = await this.config$.pipe(first()).toPromise(); - const client$ = clients$.pipe(map((clients) => clients.client)); + const legacyClient$ = clients$.pipe(map((clients) => clients.legacyClient)); - const client = { + const legacyClient = { async callAsInternalUser( endpoint: string, clientParams: Record = {}, options?: LegacyCallAPIOptions ) { - const _client = await client$.pipe(take(1)).toPromise(); + const _client = await legacyClient$.pipe(take(1)).toPromise(); return await _client.callAsInternalUser(endpoint, clientParams, options); }, asScoped(request: ScopeableRequest) { return { - callAsInternalUser: client.callAsInternalUser, + callAsInternalUser: legacyClient.callAsInternalUser, async callAsCurrentUser( endpoint: string, clientParams: Record = {}, options?: LegacyCallAPIOptions ) { - const _client = await client$.pipe(take(1)).toPromise(); + const _client = await legacyClient$.pipe(take(1)).toPromise(); return await _client .asScoped(request) .callAsCurrentUser(endpoint, clientParams, options); @@ -148,42 +152,45 @@ export class ElasticsearchService }, }; - this.client = client; + this.legacyClient = legacyClient; const esNodesCompatibility$ = pollEsNodesVersion({ - callWithInternalUser: client.callAsInternalUser, + callWithInternalUser: legacyClient.callAsInternalUser, log: this.log, ignoreVersionMismatch: config.ignoreVersionMismatch, esVersionCheckInterval: config.healthCheckDelay.asMilliseconds(), kibanaVersion: this.kibanaVersion, }).pipe(takeUntil(this.stop$), shareReplay({ refCount: true, bufferSize: 1 })); - this.createClient = ( + this.createLegacyClient = ( type: string, clientConfig: Partial = {} ) => { const finalConfig = merge({}, config, clientConfig); - return this.createClusterClient(type, finalConfig, deps.http.getAuthHeaders); + return this.createLegacyClusterClient(type, finalConfig, deps.http.getAuthHeaders); }; return { legacy: { config$: clients$.pipe(map((clients) => clients.config)), - client, - createClient: this.createClient, + client: legacyClient, + createClient: this.createLegacyClient, }, esNodesCompatibility$, status$: calculateStatus$(esNodesCompatibility$), }; } public async start() { - if (typeof this.client === 'undefined' || typeof this.createClient === 'undefined') { + if ( + typeof this.legacyClient === 'undefined' || + typeof this.createLegacyClient === 'undefined' + ) { throw new Error('ElasticsearchService needs to be setup before calling start'); } else { return { legacy: { - client: this.client, - createClient: this.createClient, + client: this.legacyClient, + createClient: this.createLegacyClient, }, }; } @@ -197,7 +204,7 @@ export class ElasticsearchService this.stop$.next(); } - private createClusterClient( + private createLegacyClusterClient( type: string, config: LegacyElasticsearchClientConfig, getAuthHeaders?: GetAuthHeaders From f268e63bb741f00348ae6aad549a40cde4fdef05 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 11:58:56 +0200 Subject: [PATCH 11/42] rename currently unused config/client observable --- .../elasticsearch/elasticsearch_service.ts | 112 ++---------------- 1 file changed, 12 insertions(+), 100 deletions(-) diff --git a/src/core/server/elasticsearch/elasticsearch_service.ts b/src/core/server/elasticsearch/elasticsearch_service.ts index d487d766efd59..5ef017aa78b2a 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.ts @@ -17,17 +17,8 @@ * under the License. */ -import { ConnectableObservable, Observable, Subscription, Subject } from 'rxjs'; -import { - filter, - first, - map, - publishReplay, - switchMap, - take, - shareReplay, - takeUntil, -} from 'rxjs/operators'; +import { Observable, Subject } from 'rxjs'; +import { first, map, shareReplay, takeUntil } from 'rxjs/operators'; import { CoreService } from '../../types'; import { merge } from '../../utils'; @@ -35,27 +26,15 @@ import { CoreContext } from '../core_context'; import { Logger } from '../logging'; import { LegacyClusterClient, - ILegacyClusterClient, ILegacyCustomClusterClient, LegacyElasticsearchClientConfig, - LegacyCallAPIOptions, } from './legacy'; import { ElasticsearchConfig, ElasticsearchConfigType } from './elasticsearch_config'; import { InternalHttpServiceSetup, GetAuthHeaders } from '../http/'; -import { - InternalElasticsearchServiceSetup, - ElasticsearchServiceStart, - ScopeableRequest, -} from './types'; +import { InternalElasticsearchServiceSetup, ElasticsearchServiceStart } from './types'; import { pollEsNodesVersion } from './version_check/ensure_es_version'; import { calculateStatus$ } from './status'; -/** @internal */ -interface CoreClusterClients { - config: ElasticsearchConfig; - legacyClient: LegacyClusterClient; -} - interface SetupDeps { http: InternalHttpServiceSetup; } @@ -65,14 +44,13 @@ export class ElasticsearchService implements CoreService { private readonly log: Logger; private readonly config$: Observable; - private subscription?: Subscription; private stop$ = new Subject(); private kibanaVersion: string; private createLegacyClient?: ( type: string, clientConfig?: Partial ) => ILegacyCustomClusterClient; - private legacyClient?: ILegacyClusterClient; + private legacyClient?: LegacyClusterClient; constructor(private readonly coreContext: CoreContext) { this.kibanaVersion = coreContext.env.packageInfo.version; @@ -85,77 +63,11 @@ export class ElasticsearchService public async setup(deps: SetupDeps): Promise { this.log.debug('Setting up elasticsearch service'); - const clients$ = this.config$.pipe( - filter(() => { - if (this.subscription !== undefined) { - this.log.error('Clients cannot be changed after they are created'); - return false; - } - - return true; - }), - switchMap( - (config) => - new Observable((subscriber) => { - this.log.debug('Creating elasticsearch client'); - - const coreClients = { - config, - legacyClient: this.createLegacyClusterClient( - 'data', - config, - deps.http.getAuthHeaders - ), - }; - - subscriber.next(coreClients); - - return () => { - this.log.debug('Closing elasticsearch client'); - - coreClients.legacyClient.close(); - }; - }) - ), - publishReplay(1) - ) as ConnectableObservable; - - this.subscription = clients$.connect(); - const config = await this.config$.pipe(first()).toPromise(); - - const legacyClient$ = clients$.pipe(map((clients) => clients.legacyClient)); - - const legacyClient = { - async callAsInternalUser( - endpoint: string, - clientParams: Record = {}, - options?: LegacyCallAPIOptions - ) { - const _client = await legacyClient$.pipe(take(1)).toPromise(); - return await _client.callAsInternalUser(endpoint, clientParams, options); - }, - asScoped(request: ScopeableRequest) { - return { - callAsInternalUser: legacyClient.callAsInternalUser, - async callAsCurrentUser( - endpoint: string, - clientParams: Record = {}, - options?: LegacyCallAPIOptions - ) { - const _client = await legacyClient$.pipe(take(1)).toPromise(); - return await _client - .asScoped(request) - .callAsCurrentUser(endpoint, clientParams, options); - }, - }; - }, - }; - - this.legacyClient = legacyClient; + this.legacyClient = this.createLegacyClusterClient('data', config, deps.http.getAuthHeaders); const esNodesCompatibility$ = pollEsNodesVersion({ - callWithInternalUser: legacyClient.callAsInternalUser, + callWithInternalUser: this.legacyClient.callAsInternalUser, log: this.log, ignoreVersionMismatch: config.ignoreVersionMismatch, esVersionCheckInterval: config.healthCheckDelay.asMilliseconds(), @@ -172,15 +84,15 @@ export class ElasticsearchService return { legacy: { - config$: clients$.pipe(map((clients) => clients.config)), - client: legacyClient, + config$: this.config$, + client: this.legacyClient, createClient: this.createLegacyClient, }, esNodesCompatibility$, status$: calculateStatus$(esNodesCompatibility$), }; } - public async start() { + public async start(): Promise { if ( typeof this.legacyClient === 'undefined' || typeof this.createLegacyClient === 'undefined' @@ -198,10 +110,10 @@ export class ElasticsearchService public async stop() { this.log.debug('Stopping elasticsearch service'); - if (this.subscription !== undefined) { - this.subscription.unsubscribe(); - } this.stop$.next(); + if (this.legacyClient) { + this.legacyClient.close(); + } } private createLegacyClusterClient( From 73f68b8f1ff65e57aab5310148e6d18054350d77 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 13:15:08 +0200 Subject: [PATCH 12/42] wire new client to service & update mocks --- .../elasticsearch/client/cluster_client.ts | 12 ++++-- src/core/server/elasticsearch/client/index.ts | 2 +- src/core/server/elasticsearch/client/mocks.ts | 18 +++++++- .../elasticsearch_service.mock.ts | 12 +++++- .../elasticsearch/elasticsearch_service.ts | 41 ++++++++++++++++--- src/core/server/elasticsearch/types.ts | 39 ++++++++++++++++-- 6 files changed, 105 insertions(+), 19 deletions(-) diff --git a/src/core/server/elasticsearch/client/cluster_client.ts b/src/core/server/elasticsearch/client/cluster_client.ts index 8106dca69cd6e..b7ee4f739bd4c 100644 --- a/src/core/server/elasticsearch/client/cluster_client.ts +++ b/src/core/server/elasticsearch/client/cluster_client.ts @@ -48,6 +48,14 @@ export interface IClusterClient { asScoped: (request: ScopeableRequest) => IScopedClusterClient; } +export interface ICustomClusterClient extends IClusterClient { + /** + * Closes the cluster client. After that client cannot be used and one should + * create a new client instance to be able to interact with Elasticsearch API. + */ + close: () => void; +} + /** @internal **/ export class ClusterClient implements IClusterClient { private readonly internalClient: Client; @@ -76,10 +84,6 @@ export class ClusterClient implements IClusterClient { return new ScopedClusterClient(this.internalFacade, scopedWrapper); } - /** - * Closes the cluster client. After that client cannot be used and one should - * create a new client instance to be able to interact with Elasticsearch API. - */ public close() { if (this.isClosed) { return; diff --git a/src/core/server/elasticsearch/client/index.ts b/src/core/server/elasticsearch/client/index.ts index 971283ed498d4..5a81f0e296e9b 100644 --- a/src/core/server/elasticsearch/client/index.ts +++ b/src/core/server/elasticsearch/client/index.ts @@ -20,5 +20,5 @@ export { IScopedClusterClient, ScopedClusterClient } from './scoped_cluster_client'; export { ClientFacade } from './client_facade'; export { ElasticsearchClientConfig } from './client_config'; -export { IClusterClient, ClusterClient } from './cluster_client'; +export { IClusterClient, ICustomClusterClient, ClusterClient } from './cluster_client'; export { configureClient } from './configure_client'; diff --git a/src/core/server/elasticsearch/client/mocks.ts b/src/core/server/elasticsearch/client/mocks.ts index 9025ca815b140..e14592100fec1 100644 --- a/src/core/server/elasticsearch/client/mocks.ts +++ b/src/core/server/elasticsearch/client/mocks.ts @@ -19,7 +19,7 @@ import { clientFacadeMock } from './client_facade.mock'; import { IScopedClusterClient } from './scoped_cluster_client'; -import { IClusterClient } from './cluster_client'; +import { IClusterClient, ICustomClusterClient } from './cluster_client'; const createScopedClusterClientMock = () => { const mock: jest.Mocked = { @@ -45,8 +45,22 @@ const createClusterClientMock = () => { return mock; }; -export const clientMock = { +const createCustomClusterClientMock = () => { + const mock: jest.Mocked = { + asInternalUser: jest.fn(), + asScoped: jest.fn(), + close: jest.fn(), + }; + + mock.asInternalUser.mockReturnValue(clientFacadeMock.create()); + mock.asScoped.mockReturnValue(createScopedClusterClientMock()); + + return mock; +}; + +export const elasticsearchClientMock = { createClusterClient: createClusterClientMock, + createCustomClusterClient: createCustomClusterClientMock, createScopedClusterClient: createScopedClusterClientMock, createFacade: clientFacadeMock.create, }; diff --git a/src/core/server/elasticsearch/elasticsearch_service.mock.ts b/src/core/server/elasticsearch/elasticsearch_service.mock.ts index fdfc48fa9f754..ce0a2fb8dd849 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.mock.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.mock.ts @@ -24,6 +24,8 @@ import { ILegacyCustomClusterClient, ILegacyScopedClusterClient, } from './legacy'; +import { IClusterClient, ICustomClusterClient } from './client'; +import { elasticsearchClientMock } from './client/mocks'; import { ElasticsearchConfig } from './elasticsearch_config'; import { ElasticsearchService } from './elasticsearch_service'; import { InternalElasticsearchServiceSetup, ElasticsearchStatusMeta } from './types'; @@ -56,6 +58,11 @@ interface MockedElasticSearchServiceSetup { }; } +interface MockedElasticSearchServiceStart extends MockedElasticSearchServiceSetup { + client: jest.Mocked; + createClient: jest.Mock; +} + const createSetupContractMock = () => { const setupContract: MockedElasticSearchServiceSetup = { legacy: { @@ -68,15 +75,16 @@ const createSetupContractMock = () => { return setupContract; }; -type MockedElasticSearchServiceStart = MockedElasticSearchServiceSetup; - const createStartContractMock = () => { const startContract: MockedElasticSearchServiceStart = { + client: elasticsearchClientMock.createClusterClient(), + createClient: jest.fn(), legacy: { createClient: jest.fn(), client: createClusterClientMock(), }, }; + startContract.createClient.mockReturnValue(elasticsearchClientMock.createCustomClusterClient()); startContract.legacy.createClient.mockReturnValue(createCustomClusterClientMock()); startContract.legacy.client.asScoped.mockReturnValue(createScopedClusterClientMock()); return startContract; diff --git a/src/core/server/elasticsearch/elasticsearch_service.ts b/src/core/server/elasticsearch/elasticsearch_service.ts index 5ef017aa78b2a..29630b9328559 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.ts @@ -29,6 +29,7 @@ import { ILegacyCustomClusterClient, LegacyElasticsearchClientConfig, } from './legacy'; +import { ClusterClient, ICustomClusterClient, ElasticsearchClientConfig } from './client'; import { ElasticsearchConfig, ElasticsearchConfigType } from './elasticsearch_config'; import { InternalHttpServiceSetup, GetAuthHeaders } from '../http/'; import { InternalElasticsearchServiceSetup, ElasticsearchServiceStart } from './types'; @@ -46,12 +47,19 @@ export class ElasticsearchService private readonly config$: Observable; private stop$ = new Subject(); private kibanaVersion: string; + private createLegacyClient?: ( type: string, clientConfig?: Partial ) => ILegacyCustomClusterClient; private legacyClient?: LegacyClusterClient; + private client?: ClusterClient; + private createCustomClient?: ( + type: string, + clientConfig?: Partial + ) => ICustomClusterClient; + constructor(private readonly coreContext: CoreContext) { this.kibanaVersion = coreContext.env.packageInfo.version; this.log = coreContext.logger.get('elasticsearch-service'); @@ -64,6 +72,7 @@ export class ElasticsearchService this.log.debug('Setting up elasticsearch service'); const config = await this.config$.pipe(first()).toPromise(); + this.client = this.createClusterClient('data', config, deps.http.getAuthHeaders); this.legacyClient = this.createLegacyClusterClient('data', config, deps.http.getAuthHeaders); const esNodesCompatibility$ = pollEsNodesVersion({ @@ -74,13 +83,14 @@ export class ElasticsearchService kibanaVersion: this.kibanaVersion, }).pipe(takeUntil(this.stop$), shareReplay({ refCount: true, bufferSize: 1 })); - this.createLegacyClient = ( - type: string, - clientConfig: Partial = {} - ) => { + this.createLegacyClient = (type, clientConfig = {}) => { const finalConfig = merge({}, config, clientConfig); return this.createLegacyClusterClient(type, finalConfig, deps.http.getAuthHeaders); }; + this.createCustomClient = (type, clientConfig = {}) => { + const finalConfig = merge({}, config, clientConfig); + return this.createClusterClient(type, finalConfig, deps.http.getAuthHeaders); + }; return { legacy: { @@ -94,12 +104,16 @@ export class ElasticsearchService } public async start(): Promise { if ( - typeof this.legacyClient === 'undefined' || - typeof this.createLegacyClient === 'undefined' + !this.client || + !this.createCustomClient || + !this.legacyClient || + !this.createLegacyClient ) { throw new Error('ElasticsearchService needs to be setup before calling start'); } else { return { + client: this.client, + createClient: this.createCustomClient, legacy: { client: this.legacyClient, createClient: this.createLegacyClient, @@ -111,11 +125,26 @@ export class ElasticsearchService public async stop() { this.log.debug('Stopping elasticsearch service'); this.stop$.next(); + if (this.client) { + this.client.close(); + } if (this.legacyClient) { this.legacyClient.close(); } } + private createClusterClient( + type: string, + config: ElasticsearchClientConfig, + getAuthHeaders?: GetAuthHeaders + ) { + return new ClusterClient( + config, + this.coreContext.logger.get('elasticsearch', type), + getAuthHeaders + ); + } + private createLegacyClusterClient( type: string, config: LegacyElasticsearchClientConfig, diff --git a/src/core/server/elasticsearch/types.ts b/src/core/server/elasticsearch/types.ts index 2b4ba4b0a0a55..a78447a381dc0 100644 --- a/src/core/server/elasticsearch/types.ts +++ b/src/core/server/elasticsearch/types.ts @@ -26,6 +26,7 @@ import { ILegacyClusterClient, ILegacyCustomClusterClient, } from './legacy'; +import { IClusterClient, ICustomClusterClient, ElasticsearchClientConfig } from './client'; import { NodesVersionCompatibility } from './version_check/ensure_es_version'; import { ServiceStatus } from '../status'; @@ -84,6 +85,37 @@ export interface ElasticsearchServiceSetup { * @public */ export interface ElasticsearchServiceStart { + /** + * A pre-configured {@link IClusterClient | Elasticsearch client} + * + * @example + * ```js + * const client = core.elasticsearch.client; + * ``` + */ + readonly client: IClusterClient; + /** + * Create application specific Elasticsearch cluster API client with customized config. See {@link IClusterClient}. + * + * @param type Unique identifier of the client + * @param clientConfig A config consists of Elasticsearch JS client options and + * valid sub-set of Elasticsearch service config. + * We fill all the missing properties in the `clientConfig` using the default + * Elasticsearch config so that we don't depend on default values set and + * controlled by underlying Elasticsearch JS client. + * We don't run validation against the passed config and expect it to be valid. + * + * @example + * ```js + * const client = elasticsearch.createClient('my-app-name', config); + * const data = await client.asInternalUser().search(); + * ``` + */ + readonly createClient: ( + type: string, + clientConfig?: Partial + ) => ICustomClusterClient; + /** * @deprecated * Provided for the backward compatibility. @@ -103,7 +135,7 @@ export interface ElasticsearchServiceStart { * * @example * ```js - * const client = elasticsearch.createCluster('my-app-name', config); + * const client = elasticsearch.legacy.createClient('my-app-name', config); * const data = await client.callAsInternalUser(); * ``` */ @@ -113,12 +145,11 @@ export interface ElasticsearchServiceStart { ) => ILegacyCustomClusterClient; /** - * A pre-configured Elasticsearch client. All Elasticsearch config value changes are processed under the hood. - * See {@link ILegacyClusterClient}. + * A pre-configured {@link ILegacyClusterClient | legacy Elasticsearch client}. * * @example * ```js - * const client = core.elasticsearch.client; + * const client = core.elasticsearch.legacy.client; * ``` */ readonly client: ILegacyClusterClient; From 2c5a48910d5b3b22185ce9d78832c4625aace79e Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 13:19:11 +0200 Subject: [PATCH 13/42] fix mock type --- src/core/server/elasticsearch/client/client_facade.mock.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/server/elasticsearch/client/client_facade.mock.ts b/src/core/server/elasticsearch/client/client_facade.mock.ts index 3cbaacdef34a9..ac92acc191cd1 100644 --- a/src/core/server/elasticsearch/client/client_facade.mock.ts +++ b/src/core/server/elasticsearch/client/client_facade.mock.ts @@ -19,8 +19,8 @@ import { ClientFacade } from './client_facade'; -const createFacadeMock = (): jest.Mocked => { - const mock: jest.Mocked = { +const createFacadeMock = () => { + const mock: DeeplyMockedKeys = { /* GENERATED */ asyncSearch: { delete: jest.fn(), @@ -387,6 +387,7 @@ const createFacadeMock = (): jest.Mocked => { }, /* /GENERATED */ }; + return mock; }; From c7ae6aad658db4e3760a1bd0942a7dc6598000d2 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 13:30:57 +0200 Subject: [PATCH 14/42] export client types --- src/core/server/elasticsearch/client/client_facade.ts | 5 +++++ src/core/server/elasticsearch/client/cluster_client.ts | 7 ++++++- src/core/server/elasticsearch/index.ts | 7 +++++++ src/core/server/index.ts | 5 +++++ 4 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/core/server/elasticsearch/client/client_facade.ts b/src/core/server/elasticsearch/client/client_facade.ts index cbc7841bc2c69..56d8da1ef568d 100644 --- a/src/core/server/elasticsearch/client/client_facade.ts +++ b/src/core/server/elasticsearch/client/client_facade.ts @@ -26,6 +26,11 @@ import { } from '@elastic/elasticsearch/lib/Transport'; import * as RequestParams from '@elastic/elasticsearch/api/requestParams'; +/** + * Facade used to query the elasticsearch cluster. + * + * @public + */ export interface ClientFacade { /* GENERATED */ asyncSearch: { diff --git a/src/core/server/elasticsearch/client/cluster_client.ts b/src/core/server/elasticsearch/client/cluster_client.ts index b7ee4f739bd4c..081eeaa1b4105 100644 --- a/src/core/server/elasticsearch/client/cluster_client.ts +++ b/src/core/server/elasticsearch/client/cluster_client.ts @@ -48,6 +48,11 @@ export interface IClusterClient { asScoped: (request: ScopeableRequest) => IScopedClusterClient; } +/** + * See {@link IClusterClient} + * + * @public + */ export interface ICustomClusterClient extends IClusterClient { /** * Closes the cluster client. After that client cannot be used and one should @@ -57,7 +62,7 @@ export interface ICustomClusterClient extends IClusterClient { } /** @internal **/ -export class ClusterClient implements IClusterClient { +export class ClusterClient implements IClusterClient, ICustomClusterClient { private readonly internalClient: Client; private readonly scopedClient: Client; diff --git a/src/core/server/elasticsearch/index.ts b/src/core/server/elasticsearch/index.ts index f5f5f5cc7b6f8..98298edfb594f 100644 --- a/src/core/server/elasticsearch/index.ts +++ b/src/core/server/elasticsearch/index.ts @@ -29,3 +29,10 @@ export { ScopeableRequest, } from './types'; export * from './legacy'; +export { + IClusterClient, + ICustomClusterClient, + ElasticsearchClientConfig, + ClientFacade, + IScopedClusterClient, +} from './client'; diff --git a/src/core/server/index.ts b/src/core/server/index.ts index 35aabab4a0b26..50a9b853dfc83 100644 --- a/src/core/server/index.ts +++ b/src/core/server/index.ts @@ -107,6 +107,11 @@ export { LegacyAPICaller, FakeRequest, ScopeableRequest, + IClusterClient, + ICustomClusterClient, + ElasticsearchClientConfig, + ClientFacade, + IScopedClusterClient, } from './elasticsearch'; export * from './elasticsearch/legacy/api_types'; export { From 93d05ee8b356c57540ea5657677c9821ee8abb27 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 13:35:45 +0200 Subject: [PATCH 15/42] add transport.request --- src/core/server/elasticsearch/client/client_facade.mock.ts | 3 +++ src/core/server/elasticsearch/client/client_facade.ts | 7 +++++++ src/core/server/elasticsearch/client/get_client_facade.ts | 3 +++ 3 files changed, 13 insertions(+) diff --git a/src/core/server/elasticsearch/client/client_facade.mock.ts b/src/core/server/elasticsearch/client/client_facade.mock.ts index ac92acc191cd1..c3448453ecdce 100644 --- a/src/core/server/elasticsearch/client/client_facade.mock.ts +++ b/src/core/server/elasticsearch/client/client_facade.mock.ts @@ -21,6 +21,9 @@ import { ClientFacade } from './client_facade'; const createFacadeMock = () => { const mock: DeeplyMockedKeys = { + transport: { + request: jest.fn(), + }, /* GENERATED */ asyncSearch: { delete: jest.fn(), diff --git a/src/core/server/elasticsearch/client/client_facade.ts b/src/core/server/elasticsearch/client/client_facade.ts index 56d8da1ef568d..dec091497251c 100644 --- a/src/core/server/elasticsearch/client/client_facade.ts +++ b/src/core/server/elasticsearch/client/client_facade.ts @@ -22,6 +22,7 @@ import { RequestBody, RequestNDBody, TransportRequestOptions, + TransportRequestParams, TransportRequestPromise, } from '@elastic/elasticsearch/lib/Transport'; import * as RequestParams from '@elastic/elasticsearch/api/requestParams'; @@ -32,6 +33,12 @@ import * as RequestParams from '@elastic/elasticsearch/api/requestParams'; * @public */ export interface ClientFacade { + transport: { + request( + params: TransportRequestParams, + options?: TransportRequestOptions + ): Promise; + }; /* GENERATED */ asyncSearch: { delete, TContext = unknown>( diff --git a/src/core/server/elasticsearch/client/get_client_facade.ts b/src/core/server/elasticsearch/client/get_client_facade.ts index 65d872d7484e9..1efe7c96606e0 100644 --- a/src/core/server/elasticsearch/client/get_client_facade.ts +++ b/src/core/server/elasticsearch/client/get_client_facade.ts @@ -47,6 +47,9 @@ export const getClientFacade = (client: Client, headers: Headers = {}): ClientFa }; return { + transport: { + request: (params, options) => client.transport.request(params, addHeaders(options)), + }, /* GENERATED */ asyncSearch: { delete: (params, options) => client.asyncSearch.delete(params, addHeaders(options)), From 41564116b7b82dada0db378ec30638c5afbe44d7 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 13:50:45 +0200 Subject: [PATCH 16/42] more doc --- .../elasticsearch/client/client_config.ts | 12 +++++++++--- .../elasticsearch/client/get_client_facade.ts | 2 ++ .../client/scoped_cluster_client.ts | 17 ++++++++++++++++- 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/core/server/elasticsearch/client/client_config.ts b/src/core/server/elasticsearch/client/client_config.ts index bb59b89ac9300..7a0514c593e42 100644 --- a/src/core/server/elasticsearch/client/client_config.ts +++ b/src/core/server/elasticsearch/client/client_config.ts @@ -24,9 +24,8 @@ import { ClientOptions, NodeOptions } from '@elastic/elasticsearch'; import { ElasticsearchConfig } from '../elasticsearch_config'; /** - * @privateRemarks Config that consumers can pass to the Elasticsearch JS client is complex and includes - * not only entries from standard `elasticsearch.*` yaml config, but also some Elasticsearch JS - * client specific options like `keepAlive` or `plugins` (that eventually will be deprecated). + * Configuration options to be used to create a {@link IClusterClient | cluster client} using the + * {@link ElasticsearchServiceStart.createClient | createClient API} * * @public */ @@ -48,6 +47,13 @@ export type ElasticsearchClientConfig = Pick< keepAlive?: boolean; }; +/** + * Parse the client options from given client config and `scoped` flag. + * + * @param config The config to generate the client options from. + * @param scoped if true, will adapt the configuration to be used by a scoped client + * (will remove basic auth and ssl certificates) + */ export function parseClientOptions( config: ElasticsearchClientConfig, scoped: boolean diff --git a/src/core/server/elasticsearch/client/get_client_facade.ts b/src/core/server/elasticsearch/client/get_client_facade.ts index 1efe7c96606e0..4855dec81c497 100644 --- a/src/core/server/elasticsearch/client/get_client_facade.ts +++ b/src/core/server/elasticsearch/client/get_client_facade.ts @@ -31,6 +31,8 @@ import { ClientFacade } from './client_facade'; * @internal */ export const getClientFacade = (client: Client, headers: Headers = {}): ClientFacade => { + // do not rename or change this method signature without adapting the API generation script + // at `src/dev/generate_es_client.ts` const addHeaders = (options?: TransportRequestOptions): TransportRequestOptions => { if (!options) { return { diff --git a/src/core/server/elasticsearch/client/scoped_cluster_client.ts b/src/core/server/elasticsearch/client/scoped_cluster_client.ts index b64edc8c63f57..d0ed122bada69 100644 --- a/src/core/server/elasticsearch/client/scoped_cluster_client.ts +++ b/src/core/server/elasticsearch/client/scoped_cluster_client.ts @@ -19,9 +19,24 @@ import { ClientFacade } from './client_facade'; -/** @public **/ +/** + * Serves the same purpose as the normal {@link ClusterClient | cluster client} but exposes + * an additional `asCurrentUser` method that doesn't use credentials of the Kibana internal + * user (as `asInternalUser` does) to request Elasticsearch API, but rather passes HTTP headers + * extracted from the current user request to the API instead. + * + * @public + **/ export interface IScopedClusterClient { + /** + * Returns a {@link ClientFacade | client facade} to be used to query the elasticsearch cluster + * on behalf of the internal Kibana user. + */ asInternalUser: () => ClientFacade; + /** + * Returns a {@link ClientFacade | client facade} to be used to query the elasticsearch cluster + * on behalf of the user that initiated the request to the Kibana server. + */ asCurrentUser: () => ClientFacade; } From 5a3fd9cea180519bff3b082743fc5602c8895a5d Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 17:15:19 +0200 Subject: [PATCH 17/42] migrate version_check to new client --- .../client/client_facade.mock.ts | 24 +++++ src/core/server/elasticsearch/client/mocks.ts | 2 + .../elasticsearch_service.test.mocks.ts | 5 +- .../elasticsearch_service.test.ts | 88 ++++++++++--------- .../elasticsearch/elasticsearch_service.ts | 2 +- .../version_check/ensure_es_version.test.ts | 71 ++++++++++----- .../version_check/ensure_es_version.ts | 17 ++-- 7 files changed, 135 insertions(+), 74 deletions(-) diff --git a/src/core/server/elasticsearch/client/client_facade.mock.ts b/src/core/server/elasticsearch/client/client_facade.mock.ts index c3448453ecdce..335c891bbb66b 100644 --- a/src/core/server/elasticsearch/client/client_facade.mock.ts +++ b/src/core/server/elasticsearch/client/client_facade.mock.ts @@ -17,8 +17,30 @@ * under the License. */ +import { ApiResponse } from '@elastic/elasticsearch'; +import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport'; import { ClientFacade } from './client_facade'; +const createApiResponse = (body: T): TransportRequestPromise> => { + const response: ApiResponse = { + body, + statusCode: 200, + warnings: [], + headers: {}, + meta: {} as any, + }; + const promise = Promise.resolve(response); + (promise as TransportRequestPromise>).abort = () => undefined; + + return promise as TransportRequestPromise>; +}; + +const createApiError = (err: any): TransportRequestPromise => { + const promise = Promise.reject(err); + (promise as TransportRequestPromise).abort = () => undefined; + return promise as TransportRequestPromise; +}; + const createFacadeMock = () => { const mock: DeeplyMockedKeys = { transport: { @@ -396,4 +418,6 @@ const createFacadeMock = () => { export const clientFacadeMock = { create: createFacadeMock, + createApiResponse, + createApiError, }; diff --git a/src/core/server/elasticsearch/client/mocks.ts b/src/core/server/elasticsearch/client/mocks.ts index e14592100fec1..58b60bf934847 100644 --- a/src/core/server/elasticsearch/client/mocks.ts +++ b/src/core/server/elasticsearch/client/mocks.ts @@ -63,4 +63,6 @@ export const elasticsearchClientMock = { createCustomClusterClient: createCustomClusterClientMock, createScopedClusterClient: createScopedClusterClientMock, createFacade: clientFacadeMock.create, + createClientResponse: clientFacadeMock.createApiResponse, + createClientError: clientFacadeMock.createApiError, }; diff --git a/src/core/server/elasticsearch/elasticsearch_service.test.mocks.ts b/src/core/server/elasticsearch/elasticsearch_service.test.mocks.ts index c30230a7847a0..955ab197ffce1 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.test.mocks.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.test.mocks.ts @@ -17,5 +17,8 @@ * under the License. */ +export const MockLegacyClusterClient = jest.fn(); +jest.mock('./legacy/cluster_client', () => ({ LegacyClusterClient: MockLegacyClusterClient })); + export const MockClusterClient = jest.fn(); -jest.mock('./legacy/cluster_client', () => ({ LegacyClusterClient: MockClusterClient })); +jest.mock('./client/cluster_client', () => ({ ClusterClient: MockClusterClient })); diff --git a/src/core/server/elasticsearch/elasticsearch_service.test.ts b/src/core/server/elasticsearch/elasticsearch_service.test.ts index 0a7068903e15c..c42ff956f2a59 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.test.ts @@ -19,7 +19,7 @@ import { first } from 'rxjs/operators'; -import { MockClusterClient } from './elasticsearch_service.test.mocks'; +import { MockLegacyClusterClient, MockClusterClient } from './elasticsearch_service.test.mocks'; import { BehaviorSubject } from 'rxjs'; import { Env } from '../config'; @@ -31,6 +31,7 @@ import { httpServiceMock } from '../http/http_service.mock'; import { ElasticsearchConfig } from './elasticsearch_config'; import { ElasticsearchService } from './elasticsearch_service'; import { elasticsearchServiceMock } from './elasticsearch_service.mock'; +import { elasticsearchClientMock } from './client/mocks'; import { duration } from 'moment'; const delay = async (durationMs: number) => @@ -56,11 +57,23 @@ configService.atPath.mockReturnValue( let env: Env; let coreContext: CoreContext; const logger = loggingSystemMock.create(); + +let mockClusterClientInstance: ReturnType; +let mockLegacyClusterClientInstance: ReturnType; + beforeEach(() => { env = Env.createDefault(getEnvOptions()); coreContext = { coreId: Symbol(), env, logger, configService: configService as any }; elasticsearchService = new ElasticsearchService(coreContext); + + MockLegacyClusterClient.mockClear(); + MockClusterClient.mockClear(); + + mockLegacyClusterClientInstance = elasticsearchServiceMock.createCustomClusterClient(); + MockLegacyClusterClient.mockImplementation(() => mockLegacyClusterClientInstance); + mockClusterClientInstance = elasticsearchClientMock.createCustomClusterClient(); + MockClusterClient.mockImplementation(() => mockClusterClientInstance); }); afterEach(() => jest.clearAllMocks()); @@ -74,31 +87,28 @@ describe('#setup', () => { ); }); - it('returns elasticsearch client as a part of the contract', async () => { - const mockClusterClientInstance = elasticsearchServiceMock.createClusterClient(); - MockClusterClient.mockImplementationOnce(() => mockClusterClientInstance); - + it('returns legacy elasticsearch client as a part of the contract', async () => { const setupContract = await elasticsearchService.setup(deps); const client = setupContract.legacy.client; - expect(mockClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(0); + expect(mockLegacyClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(0); await client.callAsInternalUser('any'); - expect(mockClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(1); + expect(mockLegacyClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(1); }); - describe('#createClient', () => { + describe('#createLegacyClient', () => { it('allows to specify config properties', async () => { const setupContract = await elasticsearchService.setup(deps); - const mockClusterClientInstance = { close: jest.fn() }; - MockClusterClient.mockImplementation(() => mockClusterClientInstance); + // reset all mocks called during setup phase + MockLegacyClusterClient.mockClear(); const customConfig = { logQueries: true }; const clusterClient = setupContract.legacy.createClient('some-custom-type', customConfig); - expect(clusterClient).toBe(mockClusterClientInstance); + expect(clusterClient).toBe(mockLegacyClusterClientInstance); - expect(MockClusterClient).toHaveBeenCalledWith( + expect(MockLegacyClusterClient).toHaveBeenCalledWith( expect.objectContaining(customConfig), expect.objectContaining({ context: ['elasticsearch', 'some-custom-type'] }), expect.any(Function) @@ -107,8 +117,9 @@ describe('#setup', () => { it('falls back to elasticsearch default config values if property not specified', async () => { const setupContract = await elasticsearchService.setup(deps); + // reset all mocks called during setup phase - MockClusterClient.mockClear(); + MockLegacyClusterClient.mockClear(); const customConfig = { hosts: ['http://8.8.8.8'], @@ -117,7 +128,7 @@ describe('#setup', () => { }; setupContract.legacy.createClient('some-custom-type', customConfig); - const config = MockClusterClient.mock.calls[0][0]; + const config = MockLegacyClusterClient.mock.calls[0][0]; expect(config).toMatchInlineSnapshot(` Object { "healthCheckDelay": "PT0.01S", @@ -137,12 +148,13 @@ describe('#setup', () => { }); it('falls back to elasticsearch config if custom config not passed', async () => { const setupContract = await elasticsearchService.setup(deps); + // reset all mocks called during setup phase - MockClusterClient.mockClear(); + MockLegacyClusterClient.mockClear(); setupContract.legacy.createClient('another-type'); - const config = MockClusterClient.mock.calls[0][0]; + const config = MockLegacyClusterClient.mock.calls[0][0]; expect(config).toMatchInlineSnapshot(` Object { "healthCheckDelay": "PT0.01S", @@ -178,8 +190,9 @@ describe('#setup', () => { ); elasticsearchService = new ElasticsearchService(coreContext); const setupContract = await elasticsearchService.setup(deps); + // reset all mocks called during setup phase - MockClusterClient.mockClear(); + MockLegacyClusterClient.mockClear(); const customConfig = { hosts: ['http://8.8.8.8'], @@ -188,7 +201,7 @@ describe('#setup', () => { }; setupContract.legacy.createClient('some-custom-type', customConfig); - const config = MockClusterClient.mock.calls[0][0]; + const config = MockLegacyClusterClient.mock.calls[0][0]; expect(config).toMatchInlineSnapshot(` Object { "healthCheckDelay": "PT2S", @@ -209,66 +222,61 @@ describe('#setup', () => { }); it('esNodeVersionCompatibility$ only starts polling when subscribed to', async (done) => { - const clusterClientInstance = elasticsearchServiceMock.createClusterClient(); - MockClusterClient.mockImplementationOnce(() => clusterClientInstance); - - clusterClientInstance.callAsInternalUser.mockRejectedValue(new Error()); + const mockedClient = elasticsearchClientMock.createFacade(); + mockedClient.nodes.info.mockRejectedValue(new Error()); + mockClusterClientInstance.asInternalUser.mockReturnValue(mockedClient); const setupContract = await elasticsearchService.setup(deps); await delay(10); - expect(clusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(0); + expect(mockedClient.nodes.info).toHaveBeenCalledTimes(0); setupContract.esNodesCompatibility$.subscribe(() => { - expect(clusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(1); + expect(mockedClient.nodes.info).toHaveBeenCalledTimes(1); done(); }); }); it('esNodeVersionCompatibility$ stops polling when unsubscribed from', async (done) => { - const mockClusterClientInstance = elasticsearchServiceMock.createClusterClient(); - MockClusterClient.mockImplementationOnce(() => mockClusterClientInstance); - - mockClusterClientInstance.callAsInternalUser.mockRejectedValue(new Error()); + const mockedClient = elasticsearchClientMock.createFacade(); + mockedClient.nodes.info.mockRejectedValue(new Error()); + mockClusterClientInstance.asInternalUser.mockReturnValue(mockedClient); const setupContract = await elasticsearchService.setup(deps); - expect(mockClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(0); + expect(mockedClient.nodes.info).toHaveBeenCalledTimes(0); const sub = setupContract.esNodesCompatibility$.subscribe(async () => { sub.unsubscribe(); await delay(100); - expect(mockClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(1); + expect(mockedClient.nodes.info).toHaveBeenCalledTimes(1); done(); }); }); }); describe('#stop', () => { - it('stops both admin and data clients', async () => { - const mockClusterClientInstance = { close: jest.fn() }; - MockClusterClient.mockImplementationOnce(() => mockClusterClientInstance); - + it('stops both legacy and new clients', async () => { await elasticsearchService.setup(deps); await elasticsearchService.stop(); + expect(mockLegacyClusterClientInstance.close).toHaveBeenCalledTimes(1); expect(mockClusterClientInstance.close).toHaveBeenCalledTimes(1); }); it('stops pollEsNodeVersions even if there are active subscriptions', async (done) => { expect.assertions(2); - const mockClusterClientInstance = elasticsearchServiceMock.createCustomClusterClient(); - - MockClusterClient.mockImplementationOnce(() => mockClusterClientInstance); - mockClusterClientInstance.callAsInternalUser.mockRejectedValue(new Error()); + const mockedClient = elasticsearchClientMock.createFacade(); + mockedClient.nodes.info.mockRejectedValue(new Error()); + mockClusterClientInstance.asInternalUser.mockReturnValue(mockedClient); const setupContract = await elasticsearchService.setup(deps); setupContract.esNodesCompatibility$.subscribe(async () => { - expect(mockClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(1); + expect(mockedClient.nodes.info).toHaveBeenCalledTimes(1); await elasticsearchService.stop(); await delay(100); - expect(mockClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(1); + expect(mockedClient.nodes.info).toHaveBeenCalledTimes(1); done(); }); }); diff --git a/src/core/server/elasticsearch/elasticsearch_service.ts b/src/core/server/elasticsearch/elasticsearch_service.ts index 29630b9328559..8fd5d0428f8cc 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.ts @@ -76,7 +76,7 @@ export class ElasticsearchService this.legacyClient = this.createLegacyClusterClient('data', config, deps.http.getAuthHeaders); const esNodesCompatibility$ = pollEsNodesVersion({ - callWithInternalUser: this.legacyClient.callAsInternalUser, + internalClient: this.client.asInternalUser(), log: this.log, ignoreVersionMismatch: config.ignoreVersionMismatch, esVersionCheckInterval: config.healthCheckDelay.asMilliseconds(), diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts index 3d1218d4a8e8b..02a018f415307 100644 --- a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts +++ b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts @@ -18,6 +18,7 @@ */ import { mapNodesVersionCompatibility, pollEsNodesVersion, NodesInfo } from './ensure_es_version'; import { loggingSystemMock } from '../../logging/logging_system.mock'; +import { elasticsearchClientMock } from '../client/mocks'; import { take, delay } from 'rxjs/operators'; import { TestScheduler } from 'rxjs/testing'; import { of } from 'rxjs'; @@ -27,6 +28,9 @@ const mockLogger = mockLoggerFactory.get('mock logger'); const KIBANA_VERSION = '5.1.0'; +const createEsSuccess = elasticsearchClientMock.createClientResponse; +const createEsError = elasticsearchClientMock.createClientError; + function createNodes(...versions: string[]): NodesInfo { const nodes = {} as any; versions @@ -111,25 +115,34 @@ describe('mapNodesVersionCompatibility', () => { }); describe('pollEsNodesVersion', () => { - const callWithInternalUser = jest.fn(); + let internalClient: ReturnType; const getTestScheduler = () => new TestScheduler((actual, expected) => { expect(actual).toEqual(expected); }); beforeEach(() => { - callWithInternalUser.mockReset(); + internalClient = elasticsearchClientMock.createFacade(); }); + const nodeInfosSuccessOnce = (infos: NodesInfo) => { + internalClient.nodes.info.mockImplementationOnce(() => createEsSuccess(infos)); + }; + const nodeInfosErrorOnce = (error: any) => { + internalClient.nodes.info.mockImplementationOnce(() => createEsError(error)); + }; + it('returns iscCompatible=false and keeps polling when a poll request throws', (done) => { expect.assertions(3); const expectedCompatibilityResults = [false, false, true]; jest.clearAllMocks(); - callWithInternalUser.mockResolvedValueOnce(createNodes('5.1.0', '5.2.0', '5.0.0')); - callWithInternalUser.mockRejectedValueOnce(new Error('mock request error')); - callWithInternalUser.mockResolvedValueOnce(createNodes('5.1.0', '5.2.0', '5.1.1-Beta1')); + + nodeInfosSuccessOnce(createNodes('5.1.0', '5.2.0', '5.0.0')); + nodeInfosErrorOnce('mock request error'); + nodeInfosSuccessOnce(createNodes('5.1.0', '5.2.0', '5.1.1-Beta1')); + pollEsNodesVersion({ - callWithInternalUser, + internalClient, esVersionCheckInterval: 1, ignoreVersionMismatch: false, kibanaVersion: KIBANA_VERSION, @@ -148,9 +161,11 @@ describe('pollEsNodesVersion', () => { it('returns compatibility results', (done) => { expect.assertions(1); const nodes = createNodes('5.1.0', '5.2.0', '5.0.0'); - callWithInternalUser.mockResolvedValueOnce(nodes); + + nodeInfosSuccessOnce(nodes); + pollEsNodesVersion({ - callWithInternalUser, + internalClient, esVersionCheckInterval: 1, ignoreVersionMismatch: false, kibanaVersion: KIBANA_VERSION, @@ -168,15 +183,15 @@ describe('pollEsNodesVersion', () => { it('only emits if the node versions changed since the previous poll', (done) => { expect.assertions(4); - callWithInternalUser.mockResolvedValueOnce(createNodes('5.1.0', '5.2.0', '5.0.0')); // emit - callWithInternalUser.mockResolvedValueOnce(createNodes('5.0.0', '5.1.0', '5.2.0')); // ignore, same versions, different ordering - callWithInternalUser.mockResolvedValueOnce(createNodes('5.1.1', '5.2.0', '5.0.0')); // emit - callWithInternalUser.mockResolvedValueOnce(createNodes('5.1.1', '5.1.2', '5.1.3')); // emit - callWithInternalUser.mockResolvedValueOnce(createNodes('5.1.1', '5.1.2', '5.1.3')); // ignore - callWithInternalUser.mockResolvedValueOnce(createNodes('5.0.0', '5.1.0', '5.2.0')); // emit, different from previous version + nodeInfosSuccessOnce(createNodes('5.1.0', '5.2.0', '5.0.0')); // emit + nodeInfosSuccessOnce(createNodes('5.0.0', '5.1.0', '5.2.0')); // ignore, same versions, different ordering + nodeInfosSuccessOnce(createNodes('5.1.1', '5.2.0', '5.0.0')); // emit + nodeInfosSuccessOnce(createNodes('5.1.1', '5.1.2', '5.1.3')); // emit + nodeInfosSuccessOnce(createNodes('5.1.1', '5.1.2', '5.1.3')); // ignore + nodeInfosSuccessOnce(createNodes('5.0.0', '5.1.0', '5.2.0')); // emit, different from previous version pollEsNodesVersion({ - callWithInternalUser, + internalClient, esVersionCheckInterval: 1, ignoreVersionMismatch: false, kibanaVersion: KIBANA_VERSION, @@ -192,14 +207,20 @@ describe('pollEsNodesVersion', () => { it('starts polling immediately and then every esVersionCheckInterval', () => { expect.assertions(1); - callWithInternalUser.mockReturnValueOnce([createNodes('5.1.0', '5.2.0', '5.0.0')]); - callWithInternalUser.mockReturnValueOnce([createNodes('5.1.1', '5.2.0', '5.0.0')]); + // @ts-expect-error we need to return an incompatible type to use the testScheduler here + internalClient.nodes.info.mockReturnValueOnce([ + { body: createNodes('5.1.0', '5.2.0', '5.0.0') }, + ]); + // @ts-expect-error we need to return an incompatible type to use the testScheduler here + internalClient.nodes.info.mockReturnValueOnce([ + { body: createNodes('5.1.1', '5.2.0', '5.0.0') }, + ]); getTestScheduler().run(({ expectObservable }) => { const expected = 'a 99ms (b|)'; const esNodesCompatibility$ = pollEsNodesVersion({ - callWithInternalUser, + internalClient, esVersionCheckInterval: 100, ignoreVersionMismatch: false, kibanaVersion: KIBANA_VERSION, @@ -227,15 +248,17 @@ describe('pollEsNodesVersion', () => { getTestScheduler().run(({ expectObservable }) => { const expected = '100ms a 99ms (b|)'; - callWithInternalUser.mockReturnValueOnce( - of(createNodes('5.1.0', '5.2.0', '5.0.0')).pipe(delay(100)) + internalClient.nodes.info.mockReturnValueOnce( + // @ts-expect-error we need to return an incompatible type to use the testScheduler here + of({ body: createNodes('5.1.0', '5.2.0', '5.0.0') }).pipe(delay(100)) ); - callWithInternalUser.mockReturnValueOnce( - of(createNodes('5.1.1', '5.2.0', '5.0.0')).pipe(delay(100)) + internalClient.nodes.info.mockReturnValueOnce( + // @ts-expect-error we need to return an incompatible type to use the testScheduler here + of({ body: createNodes('5.1.1', '5.2.0', '5.0.0') }).pipe(delay(100)) ); const esNodesCompatibility$ = pollEsNodesVersion({ - callWithInternalUser, + internalClient, esVersionCheckInterval: 10, ignoreVersionMismatch: false, kibanaVersion: KIBANA_VERSION, @@ -256,6 +279,6 @@ describe('pollEsNodesVersion', () => { }); }); - expect(callWithInternalUser).toHaveBeenCalledTimes(2); + expect(internalClient.nodes.info).toHaveBeenCalledTimes(2); }); }); diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.ts index 3f562dac22a02..6293bbabc23d0 100644 --- a/src/core/server/elasticsearch/version_check/ensure_es_version.ts +++ b/src/core/server/elasticsearch/version_check/ensure_es_version.ts @@ -29,10 +29,10 @@ import { esVersionEqualsKibana, } from './es_kibana_version_compatability'; import { Logger } from '../../logging'; -import { LegacyAPICaller } from '..'; +import { ClientFacade } from '../client'; export interface PollEsNodesVersionOptions { - callWithInternalUser: LegacyAPICaller; + internalClient: ClientFacade; log: Logger; kibanaVersion: string; ignoreVersionMismatch: boolean; @@ -137,7 +137,7 @@ function compareNodes(prev: NodesVersionCompatibility, curr: NodesVersionCompati } export const pollEsNodesVersion = ({ - callWithInternalUser, + internalClient, log, kibanaVersion, ignoreVersionMismatch, @@ -147,18 +147,19 @@ export const pollEsNodesVersion = ({ return timer(0, healthCheckInterval).pipe( exhaustMap(() => { return from( - callWithInternalUser('nodes.info', { - filterPath: ['nodes.*.version', 'nodes.*.http.publish_address', 'nodes.*.ip'], + internalClient.nodes.info({ + filter_path: ['nodes.*.version', 'nodes.*.http.publish_address', 'nodes.*.ip'], }) ).pipe( + map((response) => response.body), catchError((_err) => { return of({ nodes: {} }); }) ); }), - map((nodesInfo: NodesInfo) => - mapNodesVersionCompatibility(nodesInfo, kibanaVersion, ignoreVersionMismatch) - ), + map((nodesInfo: NodesInfo) => { + return mapNodesVersionCompatibility(nodesInfo, kibanaVersion, ignoreVersionMismatch); + }), distinctUntilChanged(compareNodes) // Only emit if there are new nodes or versions ); }; From 71a27bb8864428e652537fe48d58fe36540577ed Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 20:49:52 +0200 Subject: [PATCH 18/42] fix default port logic --- src/core/server/elasticsearch/client/client_config.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/server/elasticsearch/client/client_config.ts b/src/core/server/elasticsearch/client/client_config.ts index 7a0514c593e42..3ad175f2aa53c 100644 --- a/src/core/server/elasticsearch/client/client_config.ts +++ b/src/core/server/elasticsearch/client/client_config.ts @@ -142,7 +142,7 @@ const convertHost = ( ): NodeOptions => { const url = new URL(host); const isHTTPS = url.protocol === 'https:'; - url.port = url.port ?? isHTTPS ? '443' : '80'; + url.port = url.port ?? (isHTTPS ? '443' : '80'); if (needAuth && username && password) { url.username = username; url.password = password; From e48f3ad6a485e4315ae5b00da1e88b20068e278c Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 23:06:41 +0200 Subject: [PATCH 19/42] rename legacy client mocks --- .../elasticsearch_service.mock.ts | 8 ++--- .../elasticsearch_service.test.ts | 4 +-- .../core_service.test.mocks.ts | 4 +-- src/core/server/mocks.ts | 2 +- .../actions/server/actions_client.test.ts | 2 +- x-pack/plugins/actions/server/mocks.ts | 2 +- x-pack/plugins/alerts/server/mocks.ts | 2 +- .../server/routes/_mock_handler_arguments.ts | 2 +- .../alerts/server/routes/health.test.ts | 14 ++++---- .../server/routes/es_fields/es_fields.test.ts | 4 ++- .../server/es/cluster_client_adapter.test.ts | 2 +- .../event_log/server/es/context.test.ts | 2 +- .../plugins/licensing/server/plugin.test.ts | 33 ++++++++++--------- .../oss_telemetry/server/test_utils/index.ts | 2 +- .../server/routes/api/add_route.test.ts | 6 ++-- .../server/routes/api/delete_route.test.ts | 6 ++-- .../server/routes/api/get_route.test.ts | 6 ++-- .../server/routes/api/update_route.test.ts | 6 ++-- .../server/authentication/api_keys.test.ts | 4 +-- .../authentication/authenticator.test.ts | 2 +- .../server/authentication/index.test.ts | 4 +-- .../authentication/providers/base.mock.ts | 2 +- .../authentication/providers/basic.test.ts | 8 ++--- .../authentication/providers/http.test.ts | 4 +-- .../authentication/providers/kerberos.test.ts | 28 ++++++++-------- .../authentication/providers/oidc.test.ts | 16 ++++----- .../authentication/providers/pki.test.ts | 18 +++++----- .../authentication/providers/saml.test.ts | 30 ++++++++--------- .../authentication/providers/token.test.ts | 24 +++++++------- .../server/authentication/tokens.test.ts | 2 +- .../authorization_service.test.ts | 6 ++-- .../authorization/check_privileges.test.ts | 4 +-- .../register_privileges_with_cluster.test.ts | 2 +- x-pack/plugins/security/server/plugin.test.ts | 2 +- .../server/routes/api_keys/get.test.ts | 2 +- .../server/routes/api_keys/invalidate.test.ts | 2 +- .../server/routes/api_keys/privileges.test.ts | 2 +- .../routes/authorization/roles/delete.test.ts | 2 +- .../routes/authorization/roles/get.test.ts | 2 +- .../authorization/roles/get_all.test.ts | 2 +- .../routes/authorization/roles/put.test.ts | 2 +- .../security/server/routes/index.mock.ts | 2 +- .../server/routes/role_mapping/delete.test.ts | 2 +- .../routes/role_mapping/feature_check.test.ts | 2 +- .../server/routes/role_mapping/get.test.ts | 6 ++-- .../server/routes/role_mapping/post.test.ts | 2 +- .../routes/users/change_password.test.ts | 2 +- .../endpoint/alerts/handlers/alerts.test.ts | 4 +-- .../endpoint/routes/metadata/metadata.test.ts | 4 +-- .../routes/metadata/support/unenroll.test.ts | 8 ++--- .../endpoint/routes/policy/handlers.test.ts | 2 +- .../routes/__mocks__/request_context.ts | 2 +- .../server/lib/machine_learning/mocks.ts | 2 +- .../lib/es_deprecation_logging_apis.test.ts | 6 ++-- .../server/lib/es_migration_apis.test.ts | 2 +- .../lib/telemetry/usage_collector.test.ts | 2 +- .../server/routes/__mocks__/routes.mock.ts | 2 +- .../__tests__/get_monitor_status.test.ts | 2 +- 58 files changed, 167 insertions(+), 162 deletions(-) diff --git a/src/core/server/elasticsearch/elasticsearch_service.mock.ts b/src/core/server/elasticsearch/elasticsearch_service.mock.ts index ce0a2fb8dd849..465c8c92fbddb 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.mock.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.mock.ts @@ -183,8 +183,8 @@ export const elasticsearchServiceMock = { createInternalSetup: createInternalSetupContractMock, createSetup: createSetupContractMock, createStart: createStartContractMock, - createClusterClient: createClusterClientMock, - createCustomClusterClient: createCustomClusterClientMock, - createScopedClusterClient: createScopedClusterClientMock, - createElasticsearchClient: createElasticsearchClientMock, + createLegacyClusterClient: createClusterClientMock, + createLegacyCustomClusterClient: createCustomClusterClientMock, + createLegacyScopedClusterClient: createScopedClusterClientMock, + createLegacyElasticsearchClient: createElasticsearchClientMock, }; diff --git a/src/core/server/elasticsearch/elasticsearch_service.test.ts b/src/core/server/elasticsearch/elasticsearch_service.test.ts index c42ff956f2a59..e50f7cc7f74c5 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.test.ts @@ -59,7 +59,7 @@ let coreContext: CoreContext; const logger = loggingSystemMock.create(); let mockClusterClientInstance: ReturnType; -let mockLegacyClusterClientInstance: ReturnType; +let mockLegacyClusterClientInstance: ReturnType; beforeEach(() => { env = Env.createDefault(getEnvOptions()); @@ -70,7 +70,7 @@ beforeEach(() => { MockLegacyClusterClient.mockClear(); MockClusterClient.mockClear(); - mockLegacyClusterClientInstance = elasticsearchServiceMock.createCustomClusterClient(); + mockLegacyClusterClientInstance = elasticsearchServiceMock.createLegacyCustomClusterClient(); MockLegacyClusterClient.mockImplementation(() => mockLegacyClusterClientInstance); mockClusterClientInstance = elasticsearchClientMock.createCustomClusterClient(); MockClusterClient.mockImplementation(() => mockClusterClientInstance); 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 6f9b4b96eae9d..f7ebd18b9c488 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 4491942951c50..73d8e79069ce3 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/x-pack/plugins/actions/server/actions_client.test.ts b/x-pack/plugins/actions/server/actions_client.test.ts index 69fab828e63de..807d75cd0d701 100644 --- a/x-pack/plugins/actions/server/actions_client.test.ts +++ b/x-pack/plugins/actions/server/actions_client.test.ts @@ -25,7 +25,7 @@ import { KibanaRequest } from 'kibana/server'; const defaultKibanaIndex = '.kibana'; const savedObjectsClient = savedObjectsClientMock.create(); -const scopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); +const scopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); const actionExecutor = actionExecutorMock.create(); const executionEnqueuer = jest.fn(); const request = {} as KibanaRequest; diff --git a/x-pack/plugins/actions/server/mocks.ts b/x-pack/plugins/actions/server/mocks.ts index 1763d275c6fb0..87aa571ce6b8a 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 c94a7aba46cfa..84f79d53f218c 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 7d86d4fde7e61..548495866ec21 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 b3f41e03ebdc9..ce782dbd631a5 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/canvas/server/routes/es_fields/es_fields.test.ts b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts index c1918feb7f4ec..c2cff83f85f0d 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 feec1ee9ba008..ee6f0a301e9f8 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 3fd7e12ed8a0c..a78e47446fef8 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/licensing/server/plugin.test.ts b/x-pack/plugins/licensing/server/plugin.test.ts index bf549c18da303..6e8327e151543 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/oss_telemetry/server/test_utils/index.ts b/x-pack/plugins/oss_telemetry/server/test_utils/index.ts index 7ac9819680839..3eee1978d4f1c 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 d28e95834ca0b..406d5661c0915 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 d1e3cf89e94d9..bd2ad10c4013d 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 24e469c9ec9b2..910f9e69ea80c 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 9669c98e1349e..c20ba0a1ec7a9 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 0cdd452d459d1..631a6f9ab213c 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 3b77ea3248173..300447096af99 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 4157f0598b3d0..56d44e6628a87 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 7c71348bb8ca0..1b574e6e44c10 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 95de8ca9d00e7..22d10d1cec347 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 e6949269e3fc7..c221ecd3f1e20 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 c00374efd59b4..f04506eb01593 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 d787e76628d6d..aea5994e3ba3e 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 fd014e1a7cb81..fec03c5d04b0d 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 e9af806b36f04..851ecf8107ad2 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 ba0f23a3393ae..f83331d84e43c 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 8ad04672fdfad..e8cf37330aff2 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 4d0ab1c964741..f67e0863086bb 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 65a3d1bf1650b..364a5b737f2cf 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 }; 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 0ce7eae932fea..c102af76805b0 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 64af6fc857273..a7b958ee02de5 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 f77469552d980..40065e757e999 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 2889cf78aff83..33c52688ce8e3 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 afb67dc3bbfca..a506cc6306c53 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 ada6a1c8d2dc3..399f79f44744d 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 49123fe9c74d7..d9062bcfa2efe 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 5dbe8682c5426..66e8086d49c66 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 bec60fa149bcf..8f115f11329d3 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 c7ff2a1e68b02..24de2af5e9703 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 34961dbe27675..aec0310129f6e 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 8070b3371fcb3..ee1d550bbe24d 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 e0df59ebe7a00..9af7268a57f9c 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 ed3d1bbd0fca2..8f61d2a122f0c 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 721c020c7431b..21c7fc1340437 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/alerts/handlers/alerts.test.ts b/x-pack/plugins/security_solution/server/endpoint/alerts/handlers/alerts.test.ts index 24af9917186ba..addfae4ed16cc 100644 --- a/x-pack/plugins/security_solution/server/endpoint/alerts/handlers/alerts.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/alerts/handlers/alerts.test.ts @@ -22,8 +22,8 @@ describe('test alerts route', () => { let endpointAppContextService: EndpointAppContextService; beforeEach(() => { - mockClusterClient = elasticsearchServiceMock.createClusterClient(); - mockScopedClient = elasticsearchServiceMock.createScopedClusterClient(); + mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient(); + mockScopedClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockClusterClient.asScoped.mockReturnValue(mockScopedClient); routerMock = httpServiceMock.createRouter(); 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 f6ae2c584a346..310b9e7136a04 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', () => { } as unknown) as SearchResponse); 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/metadata/support/unenroll.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/unenroll.test.ts index 545095a6a0c16..8ea30315c6a8c 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/unenroll.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/unenroll.test.ts @@ -29,7 +29,7 @@ describe('test find all unenrolled HostId', () => { it('can find all hits with scroll', async () => { const firstHostId = '1fdca33f-799f-49f4-939c-ea4383c77671'; const secondHostId = '2fdca33f-799f-49f4-939c-ea4383c77672'; - mockScopedClient = elasticsearchServiceMock.createScopedClusterClient(); + mockScopedClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClient.callAsCurrentUser .mockImplementationOnce(() => Promise.resolve(createSearchResponse(secondHostId, 'scrollId'))) .mockImplementationOnce(noUnenrolledEndpoint); @@ -46,7 +46,7 @@ describe('test find all unenrolled HostId', () => { it('can find all unerolled endpoint host ids', async () => { const firstEndpointHostId = '1fdca33f-799f-49f4-939c-ea4383c77671'; const secondEndpointHostId = '2fdca33f-799f-49f4-939c-ea4383c77672'; - mockScopedClient = elasticsearchServiceMock.createScopedClusterClient(); + mockScopedClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClient.callAsCurrentUser .mockImplementationOnce(() => Promise.resolve(createSearchResponse(firstEndpointHostId, 'initialScrollId')) @@ -86,7 +86,7 @@ describe('test find unenrolled endpoint host id by hostId', () => { it('can find unenrolled endpoint by the host id when unenrolled', async () => { const firstEndpointHostId = '1fdca33f-799f-49f4-939c-ea4383c77671'; - mockScopedClient = elasticsearchServiceMock.createScopedClusterClient(); + mockScopedClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClient.callAsCurrentUser.mockImplementationOnce(() => Promise.resolve(createSearchResponse(firstEndpointHostId, 'initialScrollId')) ); @@ -119,7 +119,7 @@ describe('test find unenrolled endpoint host id by hostId', () => { it('find unenrolled endpoint host by the host id return undefined when no unenrolled host', async () => { const firstHostId = '1fdca33f-799f-49f4-939c-ea4383c77671'; - mockScopedClient = elasticsearchServiceMock.createScopedClusterClient(); + mockScopedClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClient.callAsCurrentUser.mockImplementationOnce(noUnenrolledEndpoint); const hostId = await findUnenrolledHostByHostId(mockScopedClient, firstHostId); expect(hostId).toBeFalsy(); 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 0578f795f4a4e..8d4524e06c49f 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 7289eb6dea161..c45dd5bd8a281 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 f044022d6db69..e9b692e4731aa 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 4ce21f1b311e8..b0dec299b2b12 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 89571a4a18231..2a4fa5cd48ded 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 7188241e10f9a..e14056439ca6b 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 861ef2d3968dc..2df770c3ce45c 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 17bbb051b1ab1..2a1417b49dca4 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 = { From bdacda34f840757fa4da6b8663a0b83b20464acd Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 30 Jun 2020 23:15:35 +0200 Subject: [PATCH 20/42] move legacy client mocks to legacy folder --- .../elasticsearch_service.mock.ts | 104 ++++-------------- src/core/server/elasticsearch/legacy/mocks.ts | 97 ++++++++++++++++ 2 files changed, 116 insertions(+), 85 deletions(-) create mode 100644 src/core/server/elasticsearch/legacy/mocks.ts diff --git a/src/core/server/elasticsearch/elasticsearch_service.mock.ts b/src/core/server/elasticsearch/elasticsearch_service.mock.ts index 465c8c92fbddb..f80b4b5b79970 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.mock.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.mock.ts @@ -18,39 +18,16 @@ */ import { BehaviorSubject } from 'rxjs'; -import { Client } from 'elasticsearch'; -import { - ILegacyClusterClient, - ILegacyCustomClusterClient, - ILegacyScopedClusterClient, -} from './legacy'; +import { ILegacyClusterClient, ILegacyCustomClusterClient } from './legacy'; import { IClusterClient, ICustomClusterClient } from './client'; import { elasticsearchClientMock } from './client/mocks'; +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; @@ -67,11 +44,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; }; @@ -81,12 +60,14 @@ const createStartContractMock = () => { createClient: jest.fn(), legacy: { createClient: jest.fn(), - client: createClusterClientMock(), + client: legacyClientMock.createClusterClient(), }, }; startContract.createClient.mockReturnValue(elasticsearchClientMock.createCustomClusterClient()); - 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; }; @@ -112,7 +93,9 @@ const createInternalSetupContractMock = () => { ...createSetupContractMock().legacy, }, }; - setupContract.legacy.client.asScoped.mockReturnValue(createScopedClusterClientMock()); + setupContract.legacy.client.asScoped.mockReturnValue( + legacyClientMock.createScopedClusterClient() + ); return setupContract; }; @@ -129,62 +112,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, - createLegacyClusterClient: createClusterClientMock, - createLegacyCustomClusterClient: createCustomClusterClientMock, - createLegacyScopedClusterClient: createScopedClusterClientMock, - createLegacyElasticsearchClient: createElasticsearchClientMock, + createLegacyClusterClient: legacyClientMock.createClusterClient, + createLegacyCustomClusterClient: legacyClientMock.createCustomClusterClient, + createLegacyScopedClusterClient: legacyClientMock.createScopedClusterClient, + createLegacyElasticsearchClient: legacyClientMock.createElasticsearchClient, }; diff --git a/src/core/server/elasticsearch/legacy/mocks.ts b/src/core/server/elasticsearch/legacy/mocks.ts new file mode 100644 index 0000000000000..7714e7032940a --- /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, +}; From 152b6dcea3752f7161e618c06a9bc8989b64f96c Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 1 Jul 2020 01:00:19 +0200 Subject: [PATCH 21/42] start adding tests --- .../client/client_config.test.ts | 455 ++++++++++++++++++ .../elasticsearch/client/client_config.ts | 13 +- .../client/scoped_cluster_client.test.ts | 41 ++ 3 files changed, 503 insertions(+), 6 deletions(-) create mode 100644 src/core/server/elasticsearch/client/client_config.test.ts create mode 100644 src/core/server/elasticsearch/client/scoped_cluster_client.test.ts diff --git a/src/core/server/elasticsearch/client/client_config.test.ts b/src/core/server/elasticsearch/client/client_config.test.ts new file mode 100644 index 0000000000000..8da0884899386 --- /dev/null +++ b/src/core/server/elasticsearch/client/client_config.test.ts @@ -0,0 +1,455 @@ +/* + * 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 { duration } from 'moment'; +import { ElasticsearchClientConfig, parseClientOptions } from './client_config'; + +const createConfig = ( + parts: Partial = {} +): ElasticsearchClientConfig => { + return { + customHeaders: {}, + logQueries: false, + sniffOnStart: false, + sniffOnConnectionFault: false, + sniffInterval: false, + requestHeadersWhitelist: ['authorization'], + hosts: ['http://localhost:80'], + ...parts, + }; +}; + +describe('parseClientOptions', () => { + describe('basic options', () => { + it('`customHeaders` option', () => { + const config = createConfig({ + customHeaders: { + foo: 'bar', + hello: 'dolly', + }, + }); + + expect(parseClientOptions(config, false)).toEqual( + expect.objectContaining({ + headers: { + foo: 'bar', + hello: 'dolly', + }, + }) + ); + }); + + it('`keepAlive` option', () => { + expect(parseClientOptions(createConfig({ keepAlive: true }), false)).toEqual( + expect.objectContaining({ agent: { keepAlive: true } }) + ); + expect(parseClientOptions(createConfig({ keepAlive: false }), false).agent).toBeUndefined(); + }); + + it('`sniff` options', () => { + expect( + parseClientOptions( + createConfig({ + sniffOnStart: true, + sniffOnConnectionFault: false, + sniffInterval: false, + }), + false + ) + ).toEqual( + expect.objectContaining({ + sniffOnStart: true, + sniffOnConnectionFault: false, + sniffInterval: false, + }) + ); + + expect( + parseClientOptions( + createConfig({ + sniffOnStart: false, + sniffOnConnectionFault: true, + sniffInterval: duration(100, 'ms'), + }), + false + ) + ).toEqual( + expect.objectContaining({ + sniffOnStart: false, + sniffOnConnectionFault: true, + sniffInterval: 100, + }) + ); + }); + + it('`hosts` option', () => { + const options = parseClientOptions( + createConfig({ + hosts: ['http://node-A:9200', 'http://node-B', 'https://node-C'], + }), + false + ); + + expect(options.nodes).toMatchInlineSnapshot(` + Array [ + Object { + "url": "http://node-a:9200/", + }, + Object { + "url": "http://node-b/", + }, + Object { + "url": "https://node-c/", + }, + ] + `); + }); + }); + + describe('authorization', () => { + describe('when `scoped` is false', () => { + it('adds the `auth` option if both `username` and `password` are set', () => { + expect( + parseClientOptions( + createConfig({ + username: 'user', + }), + false + ).auth + ).toBeUndefined(); + + expect( + parseClientOptions( + createConfig({ + password: 'pass', + }), + false + ).auth + ).toBeUndefined(); + + expect( + parseClientOptions( + createConfig({ + username: 'user', + password: 'pass', + }), + false + ) + ).toEqual( + expect.objectContaining({ + auth: { + username: 'user', + password: 'pass', + }, + }) + ); + }); + + it('adds auth to the nodes if both `username` and `password` are set', () => { + let options = parseClientOptions( + createConfig({ + username: 'user', + hosts: ['http://node-A:9200'], + }), + false + ); + expect(options.nodes).toMatchInlineSnapshot(` + Array [ + Object { + "url": "http://node-a:9200/", + }, + ] + `); + + options = parseClientOptions( + createConfig({ + password: 'pass', + hosts: ['http://node-A:9200'], + }), + false + ); + expect(options.nodes).toMatchInlineSnapshot(` + Array [ + Object { + "url": "http://node-a:9200/", + }, + ] + `); + + options = parseClientOptions( + createConfig({ + username: 'user', + password: 'pass', + hosts: ['http://node-A:9200'], + }), + false + ); + expect(options.nodes).toMatchInlineSnapshot(` + Array [ + Object { + "url": "http://user:pass@node-a:9200/", + }, + ] + `); + }); + }); + describe('when `scoped` is true', () => { + it('does not add the `auth` option even if both `username` and `password` are set', () => { + expect( + parseClientOptions( + createConfig({ + username: 'user', + password: 'pass', + }), + true + ).auth + ).toBeUndefined(); + }); + + it('does not add auth to the nodes even if both `username` and `password` are set', () => { + const options = parseClientOptions( + createConfig({ + username: 'user', + password: 'pass', + hosts: ['http://node-A:9200'], + }), + true + ); + expect(options.nodes).toMatchInlineSnapshot(` + Array [ + Object { + "url": "http://node-a:9200/", + }, + ] + `); + }); + }); + }); + + describe('ssl config', () => { + it('does not generate ssl option is ssl config is not set', () => { + expect(parseClientOptions(createConfig({}), false).ssl).toBeUndefined(); + expect(parseClientOptions(createConfig({}), true).ssl).toBeUndefined(); + }); + + it('handles the `certificateAuthorities` option', () => { + expect( + parseClientOptions( + createConfig({ + ssl: { verificationMode: 'full', certificateAuthorities: ['content-of-ca-path'] }, + }), + false + ).ssl!.ca + ).toEqual(['content-of-ca-path']); + expect( + parseClientOptions( + createConfig({ + ssl: { verificationMode: 'full', certificateAuthorities: ['content-of-ca-path'] }, + }), + true + ).ssl!.ca + ).toEqual(['content-of-ca-path']); + }); + + it('handles the `verificationMode` option', () => { + expect( + parseClientOptions( + createConfig({ + ssl: { + verificationMode: 'none', + }, + }), + false + ).ssl + ).toMatchInlineSnapshot(` + Object { + "ca": undefined, + "rejectUnauthorized": false, + } + `); + + expect( + parseClientOptions( + createConfig({ + ssl: { + verificationMode: 'certificate', + }, + }), + false + ).ssl + ).toMatchInlineSnapshot(` + Object { + "ca": undefined, + "checkServerIdentity": [Function], + "rejectUnauthorized": true, + } + `); + + expect( + parseClientOptions( + createConfig({ + ssl: { + verificationMode: 'full', + }, + }), + false + ).ssl + ).toMatchInlineSnapshot(` + Object { + "ca": undefined, + "rejectUnauthorized": true, + } + `); + + expect( + () => + parseClientOptions( + createConfig({ + ssl: { + verificationMode: 'unknown' as any, + }, + }), + false + ).ssl + ).toThrowErrorMatchingInlineSnapshot(`"Unknown ssl verificationMode: unknown"`); + + expect( + () => + parseClientOptions( + createConfig({ + ssl: { + verificationMode: undefined as any, + }, + }), + false + ).ssl + ).toThrowErrorMatchingInlineSnapshot(`"Unknown ssl verificationMode: undefined"`); + }); + + describe('`certificate`, `key` and `passphrase`', () => { + it('are not added if `key` is not present', () => { + expect( + parseClientOptions( + createConfig({ + ssl: { + verificationMode: 'full', + certificate: 'content-of-cert', + keyPassphrase: 'passphrase', + }, + }), + false + ).ssl + ).toMatchInlineSnapshot(` + Object { + "ca": undefined, + "rejectUnauthorized": true, + } + `); + }); + + it('are not added if `certificate` is not present', () => { + expect( + parseClientOptions( + createConfig({ + ssl: { + verificationMode: 'full', + key: 'content-of-key', + keyPassphrase: 'passphrase', + }, + }), + false + ).ssl + ).toMatchInlineSnapshot(` + Object { + "ca": undefined, + "rejectUnauthorized": true, + } + `); + }); + + it('are added if `key` and `certificate` are present and `scoped` is false', () => { + expect( + parseClientOptions( + createConfig({ + ssl: { + verificationMode: 'full', + key: 'content-of-key', + certificate: 'content-of-cert', + keyPassphrase: 'passphrase', + }, + }), + false + ).ssl + ).toMatchInlineSnapshot(` + Object { + "ca": undefined, + "cert": "content-of-cert", + "key": "content-of-key", + "passphrase": "passphrase", + "rejectUnauthorized": true, + } + `); + }); + + it('are not added if `scoped` is true unless `alwaysPresentCertificate` is true', () => { + expect( + parseClientOptions( + createConfig({ + ssl: { + verificationMode: 'full', + key: 'content-of-key', + certificate: 'content-of-cert', + keyPassphrase: 'passphrase', + }, + }), + true + ).ssl + ).toMatchInlineSnapshot(` + Object { + "ca": undefined, + "rejectUnauthorized": true, + } + `); + + expect( + parseClientOptions( + createConfig({ + ssl: { + verificationMode: 'full', + key: 'content-of-key', + certificate: 'content-of-cert', + keyPassphrase: 'passphrase', + alwaysPresentCertificate: true, + }, + }), + true + ).ssl + ).toMatchInlineSnapshot(` + Object { + "ca": undefined, + "cert": "content-of-cert", + "key": "content-of-key", + "passphrase": "passphrase", + "rejectUnauthorized": true, + } + `); + }); + }); + }); +}); diff --git a/src/core/server/elasticsearch/client/client_config.ts b/src/core/server/elasticsearch/client/client_config.ts index 3ad175f2aa53c..f365ca331cfea 100644 --- a/src/core/server/elasticsearch/client/client_config.ts +++ b/src/core/server/elasticsearch/client/client_config.ts @@ -70,8 +70,11 @@ export function parseClientOptions( if (config.requestTimeout != null) { clientOptions.requestTimeout = getDurationAsMs(config.requestTimeout); } - if (config.sniffInterval) { - clientOptions.sniffInterval = getDurationAsMs(config.sniffInterval); + if (config.sniffInterval != null) { + clientOptions.sniffInterval = + typeof config.sniffInterval === 'boolean' + ? config.sniffInterval + : getDurationAsMs(config.sniffInterval); } if (config.keepAlive) { clientOptions.agent = { @@ -79,9 +82,7 @@ export function parseClientOptions( }; } - // TODO: this can either be done globally here or by host in convertHost. - // Not sure which option is the best. - if (config.username && config.password) { + if (config.username && config.password && !scoped) { clientOptions.auth = { username: config.username, password: config.password, @@ -142,7 +143,7 @@ const convertHost = ( ): NodeOptions => { const url = new URL(host); const isHTTPS = url.protocol === 'https:'; - url.port = url.port ?? (isHTTPS ? '443' : '80'); + url.port = url.port || (isHTTPS ? '443' : '80'); if (needAuth && username && password) { url.username = username; url.password = password; diff --git a/src/core/server/elasticsearch/client/scoped_cluster_client.test.ts b/src/core/server/elasticsearch/client/scoped_cluster_client.test.ts new file mode 100644 index 0000000000000..c7d9b9ba9e303 --- /dev/null +++ b/src/core/server/elasticsearch/client/scoped_cluster_client.test.ts @@ -0,0 +1,41 @@ +/* + * 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 { elasticsearchClientMock } from './mocks'; +import { ScopedClusterClient } from './scoped_cluster_client'; + +describe('ScopedClusterClient', () => { + it('uses the internal client passed in the constructor', () => { + const internalClient = elasticsearchClientMock.createFacade(); + const scopedClient = elasticsearchClientMock.createFacade(); + + const scopedClusterClient = new ScopedClusterClient(internalClient, scopedClient); + + expect(scopedClusterClient.asInternalUser()).toBe(internalClient); + }); + + it('uses the scoped client passed in the constructor', () => { + const internalClient = elasticsearchClientMock.createFacade(); + const scopedClient = elasticsearchClientMock.createFacade(); + + const scopedClusterClient = new ScopedClusterClient(internalClient, scopedClient); + + expect(scopedClusterClient.asCurrentUser()).toBe(scopedClient); + }); +}); From b265759a323a945f1d633e7b4b9d7baaf1971f8e Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 1 Jul 2020 09:38:34 +0200 Subject: [PATCH 22/42] add configure_client tests --- .../client/configure_client.test.mocks.ts | 32 +++ .../client/configure_client.test.ts | 204 ++++++++++++++++++ .../elasticsearch/client/configure_client.ts | 25 ++- 3 files changed, 258 insertions(+), 3 deletions(-) create mode 100644 src/core/server/elasticsearch/client/configure_client.test.mocks.ts create mode 100644 src/core/server/elasticsearch/client/configure_client.test.ts diff --git a/src/core/server/elasticsearch/client/configure_client.test.mocks.ts b/src/core/server/elasticsearch/client/configure_client.test.mocks.ts new file mode 100644 index 0000000000000..0a74f57120fb0 --- /dev/null +++ b/src/core/server/elasticsearch/client/configure_client.test.mocks.ts @@ -0,0 +1,32 @@ +/* + * 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. + */ + +export const parseClientOptionsMock = jest.fn(); +jest.doMock('./client_config', () => ({ + parseClientOptions: parseClientOptionsMock, +})); + +export const ClientMock = jest.fn(); +jest.doMock('@elastic/elasticsearch', () => { + const actual = jest.requireActual('@elastic/elasticsearch'); + return { + ...actual, + Client: ClientMock, + }; +}); diff --git a/src/core/server/elasticsearch/client/configure_client.test.ts b/src/core/server/elasticsearch/client/configure_client.test.ts new file mode 100644 index 0000000000000..fa9c3ecc4c295 --- /dev/null +++ b/src/core/server/elasticsearch/client/configure_client.test.ts @@ -0,0 +1,204 @@ +/* + * 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 { RequestEvent, errors } from '@elastic/elasticsearch'; +import { TransportRequestParams } from '@elastic/elasticsearch/lib/Transport'; + +import { parseClientOptionsMock, ClientMock } from './configure_client.test.mocks'; +import { loggingSystemMock } from '../../logging/logging_system.mock'; +import EventEmitter from 'events'; +import type { ElasticsearchClientConfig } from './client_config'; +import { configureClient } from './configure_client'; + +const createFakeConfig = ( + parts: Partial = {} +): ElasticsearchClientConfig => { + return ({ + type: 'fake-config', + ...parts, + } as unknown) as ElasticsearchClientConfig; +}; + +const createFakeClient = () => { + const client = new EventEmitter(); + jest.spyOn(client, 'on'); + return client; +}; + +const createApiResponse = ({ + body, + statusCode = 200, + headers = {}, + warnings = [], + params, +}: { + body: T; + statusCode?: number; + headers?: Record; + warnings?: string[]; + params?: TransportRequestParams; +}): RequestEvent => { + return { + body, + statusCode, + headers, + warnings, + meta: { + request: { + params: params!, + } as any, + } as any, + }; +}; + +describe('configureClient', () => { + let logger: ReturnType; + let config: ElasticsearchClientConfig; + + beforeEach(() => { + logger = loggingSystemMock.createLogger(); + config = createFakeConfig(); + parseClientOptionsMock.mockReturnValue({}); + ClientMock.mockImplementation(() => createFakeClient()); + }); + + afterEach(() => { + parseClientOptionsMock.mockReset(); + ClientMock.mockReset(); + }); + + it('calls `parseClientOptions` with the correct parameters', () => { + configureClient(config, { logger, scoped: false }); + + expect(parseClientOptionsMock).toHaveBeenCalledTimes(1); + expect(parseClientOptionsMock).toHaveBeenCalledWith(config, false); + + parseClientOptionsMock.mockClear(); + + configureClient(config, { logger, scoped: true }); + + expect(parseClientOptionsMock).toHaveBeenCalledTimes(1); + expect(parseClientOptionsMock).toHaveBeenCalledWith(config, true); + }); + + it('constructs a client using the options returned by `parseClientOptions`', () => { + const parsedOptions = { + nodes: ['http://localhost'], + }; + parseClientOptionsMock.mockReturnValue(parsedOptions); + + const client = configureClient(config, { logger, scoped: false }); + + expect(ClientMock).toHaveBeenCalledTimes(1); + expect(ClientMock).toHaveBeenCalledWith(parsedOptions); + expect(client).toBe(ClientMock.mock.results[0].value); + }); + + it('listens to client on `response` events', () => { + const client = configureClient(config, { logger, scoped: false }); + + expect(client.on).toHaveBeenCalledTimes(1); + expect(client.on).toHaveBeenCalledWith('response', expect.any(Function)); + }); + + describe('Client logging', () => { + it('logs error when the client emits an error', () => { + const client = configureClient(config, { logger, scoped: false }); + + const response = createApiResponse({ + body: { + error: { + type: 'error message', + }, + }, + }); + client.emit('response', new errors.ResponseError(response), null); + client.emit('response', new Error('some error'), null); + + expect(loggingSystemMock.collect(logger).error).toMatchInlineSnapshot(` + Array [ + Array [ + "ResponseError: error message", + ], + Array [ + "Error: some error", + ], + ] + `); + }); + + it('logs each queries if `logQueries` is true', () => { + const client = configureClient( + createFakeConfig({ + logQueries: true, + }), + { logger, scoped: false } + ); + + const response = createApiResponse({ + body: {}, + statusCode: 200, + params: { + method: 'GET', + path: '/foo', + querystring: { hello: 'dolly' }, + }, + }); + + client.emit('response', null, response); + + expect(loggingSystemMock.collect(logger).debug).toMatchInlineSnapshot(` + Array [ + Array [ + "200 + GET /foo + hello=dolly", + Object { + "tags": Array [ + "query", + ], + }, + ], + ] + `); + }); + + it('does not log queries if `logQueries` is false', () => { + const client = configureClient( + createFakeConfig({ + logQueries: false, + }), + { logger, scoped: false } + ); + + const response = createApiResponse({ + body: {}, + statusCode: 200, + params: { + method: 'GET', + path: '/foo', + }, + }); + + client.emit('response', null, response); + + expect(logger.debug).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/src/core/server/elasticsearch/client/configure_client.ts b/src/core/server/elasticsearch/client/configure_client.ts index 74a5a7c7b0775..91af3cd5edc6b 100644 --- a/src/core/server/elasticsearch/client/configure_client.ts +++ b/src/core/server/elasticsearch/client/configure_client.ts @@ -26,21 +26,40 @@ export const configureClient = ( { logger, scoped = false }: { logger: Logger; scoped?: boolean } ): Client => { const clientOptions = parseClientOptions(config, scoped); + const client = new Client(clientOptions); + addLogging(client, logger, config.logQueries); + + return client; +}; +const addLogging = (client: Client, logger: Logger, logQueries: boolean) => { client.on('response', (err, event) => { if (err) { logger.error(`${err.name}: ${err.message}`); - } else if (config.logQueries) { + } else if (logQueries) { const params = event.meta.request.params; + + // definition is wrong, `params.querystring` can be either a string or an object + const querystring = convertQueryString(params.querystring); + logger.debug( - `${event.statusCode}\n${params.method} ${params.path}\n${params.querystring?.trim() ?? ''}`, + `${event.statusCode}\n${params.method} ${params.path}${ + querystring ? `\n${querystring}` : '' + }`, { tags: ['query'], } ); } }); +}; - return client; +const convertQueryString = (qs: string | Record | undefined): string => { + if (qs === undefined || typeof qs === 'string') { + return qs ?? ''; + } + return Object.entries(qs) + .map(([key, value]) => `${key}=${value}`) + .join('&'); }; From 9e356e8e8a4ad7066d3e0704a948b4942cd036ec Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 1 Jul 2020 10:01:35 +0200 Subject: [PATCH 23/42] add get_client_facade tests --- .../client/get_client_facade.test.ts | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 src/core/server/elasticsearch/client/get_client_facade.test.ts diff --git a/src/core/server/elasticsearch/client/get_client_facade.test.ts b/src/core/server/elasticsearch/client/get_client_facade.test.ts new file mode 100644 index 0000000000000..12160acfc435c --- /dev/null +++ b/src/core/server/elasticsearch/client/get_client_facade.test.ts @@ -0,0 +1,87 @@ +/* + * 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 '@elastic/elasticsearch'; +import { getClientFacade } from './get_client_facade'; + +// note this is only a partial version of the Client API +// as the facade is generated from our script, we can assume it is safe to +// only test behavior from arbitrary picked methods +// it also avoid to generate yet another file with a +// fully mocked `Client` interface +const getClientMock = (): DeeplyMockedKeys => { + return { + transport: { + request: jest.fn(), + }, + search: jest.fn(), + } as any; +}; + +describe('getClientFacade', () => { + let client: DeeplyMockedKeys; + + beforeEach(() => { + client = getClientMock(); + }); + + it('calls the client with correct parameters', () => { + const facade = getClientFacade(client, {}); + + facade.search({ from: 12, preference: 'pref' }, { maxRetries: 42 }); + + expect(client.search).toHaveBeenCalledTimes(1); + expect(client.search).toHaveBeenCalledWith( + { from: 12, preference: 'pref' }, + { maxRetries: 42, headers: {} } + ); + }); + + it('adds the facade headers to the `options.headers`', () => { + const facade = getClientFacade(client, { foo: 'bar', authorization: 'go' }); + + facade.search({}); + + expect(client.search).toHaveBeenCalledWith(expect.any(Object), { + headers: { foo: 'bar', authorization: 'go' }, + }); + }); + + it('respects the caller headers precedence', () => { + const facade = getClientFacade(client, { foo: 'facade', authorization: 'go' }); + + facade.search( + {}, + { + headers: { + foo: 'caller', + bar: 'true', + }, + } + ); + + expect(client.search).toHaveBeenCalledWith(expect.any(Object), { + headers: { + foo: 'caller', + authorization: 'go', + bar: 'true', + }, + }); + }); +}); From 7e49f650668f3bc55ffbcf390baa69bdf1bcab11 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 1 Jul 2020 10:13:35 +0200 Subject: [PATCH 24/42] bump client to 7.8 --- package.json | 2 +- .../client/client_facade.mock.ts | 17 ++++ .../elasticsearch/client/client_facade.ts | 86 ++++++++++++++++++- .../elasticsearch/client/get_client_facade.ts | 30 +++++++ yarn.lock | 22 ++--- 5 files changed, 143 insertions(+), 14 deletions(-) diff --git a/package.json b/package.json index ae2d362b22c71..4f444ffb6d86c 100644 --- a/package.json +++ b/package.json @@ -124,7 +124,7 @@ "@elastic/apm-rum": "^5.2.0", "@elastic/charts": "19.5.2", "@elastic/datemath": "5.0.3", - "@elastic/elasticsearch": "^7.7.1", + "@elastic/elasticsearch": "7.8.0", "@elastic/ems-client": "7.9.3", "@elastic/eui": "24.1.0", "@elastic/filesaver": "1.1.2", diff --git a/src/core/server/elasticsearch/client/client_facade.mock.ts b/src/core/server/elasticsearch/client/client_facade.mock.ts index 335c891bbb66b..a9f6a74bfc0a3 100644 --- a/src/core/server/elasticsearch/client/client_facade.mock.ts +++ b/src/core/server/elasticsearch/client/client_facade.mock.ts @@ -53,7 +53,10 @@ const createFacadeMock = () => { submit: jest.fn(), }, autoscaling: { + deleteAutoscalingPolicy: jest.fn(), getAutoscalingDecision: jest.fn(), + getAutoscalingPolicy: jest.fn(), + putAutoscalingPolicy: jest.fn(), }, bulk: jest.fn(), cat: { @@ -102,10 +105,13 @@ const createFacadeMock = () => { cluster: { allocationExplain: jest.fn(), deleteComponentTemplate: jest.fn(), + deleteVotingConfigExclusions: jest.fn(), + existsComponentTemplate: jest.fn(), getComponentTemplate: jest.fn(), getSettings: jest.fn(), health: jest.fn(), pendingTasks: jest.fn(), + postVotingConfigExclusions: jest.fn(), putComponentTemplate: jest.fn(), putSettings: jest.fn(), remoteInfo: jest.fn(), @@ -164,9 +170,11 @@ const createFacadeMock = () => { delete: jest.fn(), deleteAlias: jest.fn(), deleteDataStream: jest.fn(), + deleteIndexTemplate: jest.fn(), deleteTemplate: jest.fn(), exists: jest.fn(), existsAlias: jest.fn(), + existsIndexTemplate: jest.fn(), existsTemplate: jest.fn(), existsType: jest.fn(), flush: jest.fn(), @@ -177,12 +185,14 @@ const createFacadeMock = () => { getAlias: jest.fn(), getDataStreams: jest.fn(), getFieldMapping: jest.fn(), + getIndexTemplate: jest.fn(), getMapping: jest.fn(), getSettings: jest.fn(), getTemplate: jest.fn(), getUpgrade: jest.fn(), open: jest.fn(), putAlias: jest.fn(), + putIndexTemplate: jest.fn(), putMapping: jest.fn(), putSettings: jest.fn(), putTemplate: jest.fn(), @@ -193,6 +203,7 @@ const createFacadeMock = () => { segments: jest.fn(), shardStores: jest.fn(), shrink: jest.fn(), + simulateIndexTemplate: jest.fn(), split: jest.fn(), stats: jest.fn(), unfreeze: jest.fn(), @@ -316,6 +327,12 @@ const createFacadeMock = () => { search: jest.fn(), searchShards: jest.fn(), searchTemplate: jest.fn(), + searchableSnapshots: { + clearCache: jest.fn(), + mount: jest.fn(), + repositoryStats: jest.fn(), + stats: jest.fn(), + }, security: { authenticate: jest.fn(), changePassword: jest.fn(), diff --git a/src/core/server/elasticsearch/client/client_facade.ts b/src/core/server/elasticsearch/client/client_facade.ts index dec091497251c..0e7b12337853c 100644 --- a/src/core/server/elasticsearch/client/client_facade.ts +++ b/src/core/server/elasticsearch/client/client_facade.ts @@ -59,10 +59,26 @@ export interface ClientFacade { ): TransportRequestPromise>; }; autoscaling: { + deleteAutoscalingPolicy, TContext = unknown>( + params?: RequestParams.AutoscalingDeleteAutoscalingPolicy, + options?: TransportRequestOptions + ): TransportRequestPromise>; getAutoscalingDecision, TContext = unknown>( params?: RequestParams.AutoscalingGetAutoscalingDecision, options?: TransportRequestOptions ): TransportRequestPromise>; + getAutoscalingPolicy, TContext = unknown>( + params?: RequestParams.AutoscalingGetAutoscalingPolicy, + options?: TransportRequestOptions + ): TransportRequestPromise>; + putAutoscalingPolicy< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.AutoscalingPutAutoscalingPolicy, + options?: TransportRequestOptions + ): TransportRequestPromise>; }; bulk< TResponse = Record, @@ -265,6 +281,14 @@ export interface ClientFacade { params?: RequestParams.ClusterDeleteComponentTemplate, options?: TransportRequestOptions ): TransportRequestPromise>; + deleteVotingConfigExclusions, TContext = unknown>( + params?: RequestParams.ClusterDeleteVotingConfigExclusions, + options?: TransportRequestOptions + ): TransportRequestPromise>; + existsComponentTemplate, TContext = unknown>( + params?: RequestParams.ClusterExistsComponentTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; getComponentTemplate, TContext = unknown>( params?: RequestParams.ClusterGetComponentTemplate, options?: TransportRequestOptions @@ -281,6 +305,10 @@ export interface ClientFacade { params?: RequestParams.ClusterPendingTasks, options?: TransportRequestOptions ): TransportRequestPromise>; + postVotingConfigExclusions, TContext = unknown>( + params?: RequestParams.ClusterPostVotingConfigExclusions, + options?: TransportRequestOptions + ): TransportRequestPromise>; putComponentTemplate< TResponse = Record, TRequestBody extends RequestBody = Record, @@ -551,6 +579,10 @@ export interface ClientFacade { params?: RequestParams.IndicesDeleteDataStream, options?: TransportRequestOptions ): TransportRequestPromise>; + deleteIndexTemplate, TContext = unknown>( + params?: RequestParams.IndicesDeleteIndexTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; deleteTemplate, TContext = unknown>( params?: RequestParams.IndicesDeleteTemplate, options?: TransportRequestOptions @@ -563,6 +595,10 @@ export interface ClientFacade { params?: RequestParams.IndicesExistsAlias, options?: TransportRequestOptions ): TransportRequestPromise>; + existsIndexTemplate, TContext = unknown>( + params?: RequestParams.IndicesExistsIndexTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; existsTemplate, TContext = unknown>( params?: RequestParams.IndicesExistsTemplate, options?: TransportRequestOptions @@ -603,6 +639,10 @@ export interface ClientFacade { params?: RequestParams.IndicesGetFieldMapping, options?: TransportRequestOptions ): TransportRequestPromise>; + getIndexTemplate, TContext = unknown>( + params?: RequestParams.IndicesGetIndexTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; getMapping, TContext = unknown>( params?: RequestParams.IndicesGetMapping, options?: TransportRequestOptions @@ -631,6 +671,14 @@ export interface ClientFacade { params?: RequestParams.IndicesPutAlias, options?: TransportRequestOptions ): TransportRequestPromise>; + putIndexTemplate< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IndicesPutIndexTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; putMapping< TResponse = Record, TRequestBody extends RequestBody = Record, @@ -691,6 +739,14 @@ export interface ClientFacade { params?: RequestParams.IndicesShrink, options?: TransportRequestOptions ): TransportRequestPromise>; + simulateIndexTemplate< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.IndicesSimulateIndexTemplate, + options?: TransportRequestOptions + ): TransportRequestPromise>; split< TResponse = Record, TRequestBody extends RequestBody = Record, @@ -839,8 +895,12 @@ export interface ClientFacade { params?: RequestParams.MlDeleteDatafeed, options?: TransportRequestOptions ): TransportRequestPromise>; - deleteExpiredData, TContext = unknown>( - params?: RequestParams.MlDeleteExpiredData, + deleteExpiredData< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.MlDeleteExpiredData, options?: TransportRequestOptions ): TransportRequestPromise>; deleteFilter, TContext = unknown>( @@ -1350,6 +1410,28 @@ export interface ClientFacade { params?: RequestParams.SearchTemplate, options?: TransportRequestOptions ): TransportRequestPromise>; + searchableSnapshots: { + clearCache, TContext = unknown>( + params?: RequestParams.SearchableSnapshotsClearCache, + options?: TransportRequestOptions + ): TransportRequestPromise>; + mount< + TResponse = Record, + TRequestBody extends RequestBody = Record, + TContext = unknown + >( + params?: RequestParams.SearchableSnapshotsMount, + options?: TransportRequestOptions + ): TransportRequestPromise>; + repositoryStats, TContext = unknown>( + params?: RequestParams.SearchableSnapshotsRepositoryStats, + options?: TransportRequestOptions + ): TransportRequestPromise>; + stats, TContext = unknown>( + params?: RequestParams.SearchableSnapshotsStats, + options?: TransportRequestOptions + ): TransportRequestPromise>; + }; security: { authenticate, TContext = unknown>( params?: RequestParams.SecurityAuthenticate, diff --git a/src/core/server/elasticsearch/client/get_client_facade.ts b/src/core/server/elasticsearch/client/get_client_facade.ts index 4855dec81c497..8818fbf01390c 100644 --- a/src/core/server/elasticsearch/client/get_client_facade.ts +++ b/src/core/server/elasticsearch/client/get_client_facade.ts @@ -59,8 +59,14 @@ export const getClientFacade = (client: Client, headers: Headers = {}): ClientFa submit: (params, options) => client.asyncSearch.submit(params, addHeaders(options)), }, autoscaling: { + deleteAutoscalingPolicy: (params, options) => + client.autoscaling.deleteAutoscalingPolicy(params, addHeaders(options)), getAutoscalingDecision: (params, options) => client.autoscaling.getAutoscalingDecision(params, addHeaders(options)), + getAutoscalingPolicy: (params, options) => + client.autoscaling.getAutoscalingPolicy(params, addHeaders(options)), + putAutoscalingPolicy: (params, options) => + client.autoscaling.putAutoscalingPolicy(params, addHeaders(options)), }, bulk: (params, options) => client.bulk(params, addHeaders(options)), cat: { @@ -117,11 +123,17 @@ export const getClientFacade = (client: Client, headers: Headers = {}): ClientFa client.cluster.allocationExplain(params, addHeaders(options)), deleteComponentTemplate: (params, options) => client.cluster.deleteComponentTemplate(params, addHeaders(options)), + deleteVotingConfigExclusions: (params, options) => + client.cluster.deleteVotingConfigExclusions(params, addHeaders(options)), + existsComponentTemplate: (params, options) => + client.cluster.existsComponentTemplate(params, addHeaders(options)), getComponentTemplate: (params, options) => client.cluster.getComponentTemplate(params, addHeaders(options)), getSettings: (params, options) => client.cluster.getSettings(params, addHeaders(options)), health: (params, options) => client.cluster.health(params, addHeaders(options)), pendingTasks: (params, options) => client.cluster.pendingTasks(params, addHeaders(options)), + postVotingConfigExclusions: (params, options) => + client.cluster.postVotingConfigExclusions(params, addHeaders(options)), putComponentTemplate: (params, options) => client.cluster.putComponentTemplate(params, addHeaders(options)), putSettings: (params, options) => client.cluster.putSettings(params, addHeaders(options)), @@ -185,10 +197,14 @@ export const getClientFacade = (client: Client, headers: Headers = {}): ClientFa deleteAlias: (params, options) => client.indices.deleteAlias(params, addHeaders(options)), deleteDataStream: (params, options) => client.indices.deleteDataStream(params, addHeaders(options)), + deleteIndexTemplate: (params, options) => + client.indices.deleteIndexTemplate(params, addHeaders(options)), deleteTemplate: (params, options) => client.indices.deleteTemplate(params, addHeaders(options)), exists: (params, options) => client.indices.exists(params, addHeaders(options)), existsAlias: (params, options) => client.indices.existsAlias(params, addHeaders(options)), + existsIndexTemplate: (params, options) => + client.indices.existsIndexTemplate(params, addHeaders(options)), existsTemplate: (params, options) => client.indices.existsTemplate(params, addHeaders(options)), existsType: (params, options) => client.indices.existsType(params, addHeaders(options)), @@ -202,12 +218,16 @@ export const getClientFacade = (client: Client, headers: Headers = {}): ClientFa client.indices.getDataStreams(params, addHeaders(options)), getFieldMapping: (params, options) => client.indices.getFieldMapping(params, addHeaders(options)), + getIndexTemplate: (params, options) => + client.indices.getIndexTemplate(params, addHeaders(options)), getMapping: (params, options) => client.indices.getMapping(params, addHeaders(options)), getSettings: (params, options) => client.indices.getSettings(params, addHeaders(options)), getTemplate: (params, options) => client.indices.getTemplate(params, addHeaders(options)), getUpgrade: (params, options) => client.indices.getUpgrade(params, addHeaders(options)), open: (params, options) => client.indices.open(params, addHeaders(options)), putAlias: (params, options) => client.indices.putAlias(params, addHeaders(options)), + putIndexTemplate: (params, options) => + client.indices.putIndexTemplate(params, addHeaders(options)), putMapping: (params, options) => client.indices.putMapping(params, addHeaders(options)), putSettings: (params, options) => client.indices.putSettings(params, addHeaders(options)), putTemplate: (params, options) => client.indices.putTemplate(params, addHeaders(options)), @@ -219,6 +239,8 @@ export const getClientFacade = (client: Client, headers: Headers = {}): ClientFa segments: (params, options) => client.indices.segments(params, addHeaders(options)), shardStores: (params, options) => client.indices.shardStores(params, addHeaders(options)), shrink: (params, options) => client.indices.shrink(params, addHeaders(options)), + simulateIndexTemplate: (params, options) => + client.indices.simulateIndexTemplate(params, addHeaders(options)), split: (params, options) => client.indices.split(params, addHeaders(options)), stats: (params, options) => client.indices.stats(params, addHeaders(options)), unfreeze: (params, options) => client.indices.unfreeze(params, addHeaders(options)), @@ -376,6 +398,14 @@ export const getClientFacade = (client: Client, headers: Headers = {}): ClientFa search: (params, options) => client.search(params, addHeaders(options)), searchShards: (params, options) => client.searchShards(params, addHeaders(options)), searchTemplate: (params, options) => client.searchTemplate(params, addHeaders(options)), + searchableSnapshots: { + clearCache: (params, options) => + client.searchableSnapshots.clearCache(params, addHeaders(options)), + mount: (params, options) => client.searchableSnapshots.mount(params, addHeaders(options)), + repositoryStats: (params, options) => + client.searchableSnapshots.repositoryStats(params, addHeaders(options)), + stats: (params, options) => client.searchableSnapshots.stats(params, addHeaders(options)), + }, security: { authenticate: (params, options) => client.security.authenticate(params, addHeaders(options)), changePassword: (params, options) => diff --git a/yarn.lock b/yarn.lock index 7d8fbb95ed84f..7a93c29fcfd82 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2169,28 +2169,28 @@ utility-types "^3.10.0" uuid "^3.3.2" -"@elastic/elasticsearch@^7.4.0": - version "7.4.0" - resolved "https://registry.yarnpkg.com/@elastic/elasticsearch/-/elasticsearch-7.4.0.tgz#57f4066acf25e9d4e9b4f6376088433aae6f25d4" - integrity sha512-HpEKHH6mHQRvea3lw4NNJw9ZUS1KmkpwWKHucaHi1svDn+/fEAwY0wD8egL1vZJo4ZmWfCQMjVqGL+Hoy1HYRw== +"@elastic/elasticsearch@7.8.0": + version "7.8.0" + resolved "https://registry.yarnpkg.com/@elastic/elasticsearch/-/elasticsearch-7.8.0.tgz#3f9ee54fe8ef79874ebd231db03825fa500a7111" + integrity sha512-rUOTNN1At0KoN0Fcjd6+J7efghuURnoMTB/od9EMK6Mcdebi6N3z5ulShTsKRn6OanS9Eq3l/OmheQY1Y+WLcg== dependencies: debug "^4.1.1" decompress-response "^4.2.0" - into-stream "^5.1.0" ms "^2.1.1" - once "^1.4.0" pump "^3.0.0" + secure-json-parse "^2.1.0" -"@elastic/elasticsearch@^7.7.1": - version "7.7.1" - resolved "https://registry.yarnpkg.com/@elastic/elasticsearch/-/elasticsearch-7.7.1.tgz#ad95145fcd779206d101560cb90cdeb3041d2984" - integrity sha512-OzCitXAMQ4pC6EwtPCO0KBygjDFcBMBrJ6pBguYuZxtMbRLOPjcS1Er31N0+J6mp2Q8pU0HGm1FAGfGe6FJReQ== +"@elastic/elasticsearch@^7.4.0": + version "7.4.0" + resolved "https://registry.yarnpkg.com/@elastic/elasticsearch/-/elasticsearch-7.4.0.tgz#57f4066acf25e9d4e9b4f6376088433aae6f25d4" + integrity sha512-HpEKHH6mHQRvea3lw4NNJw9ZUS1KmkpwWKHucaHi1svDn+/fEAwY0wD8egL1vZJo4ZmWfCQMjVqGL+Hoy1HYRw== dependencies: debug "^4.1.1" decompress-response "^4.2.0" + into-stream "^5.1.0" ms "^2.1.1" + once "^1.4.0" pump "^3.0.0" - secure-json-parse "^2.1.0" "@elastic/ems-client@7.9.3": version "7.9.3" From bda204eef929700d5307283f64f1d1f284c85ffa Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 1 Jul 2020 12:08:14 +0200 Subject: [PATCH 25/42] add cluster_client tests --- .../client/cluster_client.test.mocks.ts | 28 ++ .../client/cluster_client.test.ts | 287 ++++++++++++++++++ .../elasticsearch/client/cluster_client.ts | 2 +- 3 files changed, 316 insertions(+), 1 deletion(-) create mode 100644 src/core/server/elasticsearch/client/cluster_client.test.mocks.ts create mode 100644 src/core/server/elasticsearch/client/cluster_client.test.ts diff --git a/src/core/server/elasticsearch/client/cluster_client.test.mocks.ts b/src/core/server/elasticsearch/client/cluster_client.test.mocks.ts new file mode 100644 index 0000000000000..35d0093c16189 --- /dev/null +++ b/src/core/server/elasticsearch/client/cluster_client.test.mocks.ts @@ -0,0 +1,28 @@ +/* + * 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. + */ + +export const configureClientMock = jest.fn(); +jest.doMock('./configure_client', () => ({ + configureClient: configureClientMock, +})); + +export const getClientFacadeMock = jest.fn(); +jest.doMock('./get_client_facade', () => ({ + getClientFacade: getClientFacadeMock, +})); diff --git a/src/core/server/elasticsearch/client/cluster_client.test.ts b/src/core/server/elasticsearch/client/cluster_client.test.ts new file mode 100644 index 0000000000000..e02d16b3049a4 --- /dev/null +++ b/src/core/server/elasticsearch/client/cluster_client.test.ts @@ -0,0 +1,287 @@ +/* + * 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 type { Client } from '@elastic/elasticsearch'; +import { configureClientMock, getClientFacadeMock } from './cluster_client.test.mocks'; +import { loggingSystemMock } from '../../logging/logging_system.mock'; +import { httpServerMock } from '../../http/http_server.mocks'; +import { GetAuthHeaders } from '../../http'; +import { elasticsearchClientMock } from './mocks'; +import { ClusterClient } from './cluster_client'; +import { ElasticsearchClientConfig } from './client_config'; + +const createClientMock = (): jest.Mocked => { + return ({ + close: jest.fn(), + } as unknown) as jest.Mocked; +}; + +const createConfig = ( + parts: Partial = {} +): ElasticsearchClientConfig => { + return { + logQueries: false, + sniffOnStart: false, + sniffOnConnectionFault: false, + sniffInterval: false, + requestHeadersWhitelist: ['authorization'], + customHeaders: {}, + hosts: ['http://localhost'], + ...parts, + }; +}; + +describe('ClusterClient', () => { + let logger: ReturnType; + let getAuthHeaders: jest.MockedFunction; + let internalClient: jest.Mocked; + let scopedClient: jest.Mocked; + let internalFacade: ReturnType; + + beforeEach(() => { + logger = loggingSystemMock.createLogger(); + internalClient = createClientMock(); + scopedClient = createClientMock(); + internalFacade = elasticsearchClientMock.createFacade(); + getAuthHeaders = jest.fn().mockImplementation(() => ({ + authorization: 'auth', + foo: 'bar', + })); + + configureClientMock.mockImplementation((config, { scoped = false }) => { + return scoped ? scopedClient : internalClient; + }); + + getClientFacadeMock.mockImplementation((client) => { + if (client === internalClient) { + return internalFacade; + } + return elasticsearchClientMock.createFacade(); + }); + }); + + afterEach(() => { + configureClientMock.mockReset(); + getClientFacadeMock.mockReset(); + }); + + it('creates a single internal and scoped client during initialization', () => { + const config = createConfig(); + + new ClusterClient(config, logger, getAuthHeaders); + + expect(configureClientMock).toHaveBeenCalledTimes(2); + expect(configureClientMock).toHaveBeenCalledWith(config, { logger }); + expect(configureClientMock).toHaveBeenCalledWith(config, { logger, scoped: true }); + + expect(getClientFacadeMock).toHaveBeenCalledTimes(1); + expect(getClientFacadeMock).toHaveBeenCalledWith(internalClient); + }); + + describe('#asInternalUser', () => { + it('returns the facade using the internal client', () => { + const clusterClient = new ClusterClient(createConfig(), logger, getAuthHeaders); + + getClientFacadeMock.mockClear(); + + expect(clusterClient.asInternalUser()).toBe(internalFacade); + expect(getClientFacadeMock).not.toHaveBeenCalled(); + }); + }); + + describe('#asScoped', () => { + it('returns a scoped cluster client bound to the request', () => { + const clusterClient = new ClusterClient(createConfig(), logger, getAuthHeaders); + const request = httpServerMock.createKibanaRequest(); + + getClientFacadeMock.mockClear(); + + const scopedClusterClient = clusterClient.asScoped(request); + + expect(getClientFacadeMock).toHaveBeenCalledTimes(1); + expect(getClientFacadeMock).toHaveBeenCalledWith(scopedClient, expect.any(Object)); + + expect(scopedClusterClient.asInternalUser()).toBe(clusterClient.asInternalUser()); + expect(scopedClusterClient.asCurrentUser()).toBe(getClientFacadeMock.mock.results[0].value); + }); + + it('returns a distinct facade on each call', () => { + const clusterClient = new ClusterClient(createConfig(), logger, getAuthHeaders); + const request = httpServerMock.createKibanaRequest(); + + getClientFacadeMock.mockClear(); + + const scopedClusterClient1 = clusterClient.asScoped(request); + const scopedClusterClient2 = clusterClient.asScoped(request); + + expect(getClientFacadeMock).toHaveBeenCalledTimes(2); + + expect(scopedClusterClient1).not.toBe(scopedClusterClient2); + expect(scopedClusterClient1.asInternalUser()).toBe(scopedClusterClient2.asInternalUser()); + }); + + it('creates a scoped facade with filtered request headers', () => { + const config = createConfig({ + requestHeadersWhitelist: ['foo'], + }); + getAuthHeaders.mockReturnValue({}); + + const clusterClient = new ClusterClient(config, logger, getAuthHeaders); + const request = httpServerMock.createKibanaRequest({ + headers: { + foo: 'bar', + hello: 'dolly', + }, + }); + + getClientFacadeMock.mockClear(); + + clusterClient.asScoped(request); + + expect(getClientFacadeMock).toHaveBeenCalledTimes(1); + expect(getClientFacadeMock).toHaveBeenCalledWith(scopedClient, { + foo: 'bar', + }); + }); + + it('creates a scoped facade with filtered auth headers', () => { + const config = createConfig({ + requestHeadersWhitelist: ['authorization'], + }); + getAuthHeaders.mockReturnValue({ + authorization: 'auth', + other: 'nope', + }); + + const clusterClient = new ClusterClient(config, logger, getAuthHeaders); + const request = httpServerMock.createKibanaRequest({}); + + getClientFacadeMock.mockClear(); + + clusterClient.asScoped(request); + + expect(getClientFacadeMock).toHaveBeenCalledTimes(1); + expect(getClientFacadeMock).toHaveBeenCalledWith(scopedClient, { + authorization: 'auth', + }); + }); + + it('respects auth headers precedence', () => { + const config = createConfig({ + requestHeadersWhitelist: ['authorization'], + }); + getAuthHeaders.mockReturnValue({ + authorization: 'auth', + other: 'nope', + }); + + const clusterClient = new ClusterClient(config, logger, getAuthHeaders); + const request = httpServerMock.createKibanaRequest({ + headers: { + authorization: 'override', + }, + }); + + getClientFacadeMock.mockClear(); + + clusterClient.asScoped(request); + + expect(getClientFacadeMock).toHaveBeenCalledTimes(1); + expect(getClientFacadeMock).toHaveBeenCalledWith(scopedClient, { + authorization: 'auth', + }); + }); + + it('filter headers when called with a `FakeRequest`', () => { + const config = createConfig({ + requestHeadersWhitelist: ['authorization'], + }); + getAuthHeaders.mockReturnValue({}); + + const clusterClient = new ClusterClient(config, logger, getAuthHeaders); + const request = { + headers: { + authorization: 'auth', + hello: 'dolly', + }, + }; + + getClientFacadeMock.mockClear(); + + clusterClient.asScoped(request); + + expect(getClientFacadeMock).toHaveBeenCalledTimes(1); + expect(getClientFacadeMock).toHaveBeenCalledWith(scopedClient, { + authorization: 'auth', + }); + }); + + it('does not add auth headers when called with a `FakeRequest`', () => { + const config = createConfig({ + requestHeadersWhitelist: ['authorization', 'foo'], + }); + getAuthHeaders.mockReturnValue({ + authorization: 'auth', + }); + + const clusterClient = new ClusterClient(config, logger, getAuthHeaders); + const request = { + headers: { + foo: 'bar', + hello: 'dolly', + }, + }; + + getClientFacadeMock.mockClear(); + + clusterClient.asScoped(request); + + expect(getClientFacadeMock).toHaveBeenCalledTimes(1); + expect(getClientFacadeMock).toHaveBeenCalledWith(scopedClient, { + foo: 'bar', + }); + }); + }); + + describe('#close', () => { + it('closes both underlying clients', () => { + const clusterClient = new ClusterClient(createConfig(), logger, getAuthHeaders); + + clusterClient.close(); + + expect(internalClient.close).toHaveBeenCalledTimes(1); + expect(scopedClient.close).toHaveBeenCalledTimes(1); + }); + + it('does nothing after the first call', () => { + const clusterClient = new ClusterClient(createConfig(), logger, getAuthHeaders); + + clusterClient.close(); + + expect(internalClient.close).toHaveBeenCalledTimes(1); + expect(scopedClient.close).toHaveBeenCalledTimes(1); + + clusterClient.close(); + clusterClient.close(); + + expect(internalClient.close).toHaveBeenCalledTimes(1); + expect(scopedClient.close).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/src/core/server/elasticsearch/client/cluster_client.ts b/src/core/server/elasticsearch/client/cluster_client.ts index 081eeaa1b4105..fae0be98ee0e8 100644 --- a/src/core/server/elasticsearch/client/cluster_client.ts +++ b/src/core/server/elasticsearch/client/cluster_client.ts @@ -101,7 +101,7 @@ export class ClusterClient implements IClusterClient, ICustomClusterClient { private getScopedHeaders(request: ScopeableRequest): Headers { if (!isRealRequest(request)) { - return request?.headers ?? {}; + return filterHeaders(request?.headers ?? {}, this.config.requestHeadersWhitelist); } const authHeaders = this.getAuthHeaders(request); const headers = ensureRawRequest(request).headers; From 28b8cfc3c687cf883620b2bc85273e4b18849d31 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 1 Jul 2020 12:37:53 +0200 Subject: [PATCH 26/42] expose new client on internal contract only --- .../elasticsearch_service.mock.ts | 22 +++-- .../elasticsearch/elasticsearch_service.ts | 16 ++-- src/core/server/elasticsearch/index.ts | 1 + src/core/server/elasticsearch/types.ts | 83 ++++++++++--------- src/core/server/index.ts | 5 -- src/core/server/internal_types.ts | 7 +- src/core/server/mocks.ts | 2 +- src/core/server/plugins/plugin_context.ts | 4 +- 8 files changed, 79 insertions(+), 61 deletions(-) diff --git a/src/core/server/elasticsearch/elasticsearch_service.mock.ts b/src/core/server/elasticsearch/elasticsearch_service.mock.ts index f80b4b5b79970..c67f575525786 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.mock.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.mock.ts @@ -35,7 +35,9 @@ interface MockedElasticSearchServiceSetup { }; } -interface MockedElasticSearchServiceStart extends MockedElasticSearchServiceSetup { +type MockedElasticSearchServiceStart = MockedElasticSearchServiceSetup; + +interface MockedInternalElasticSearchServiceStart extends MockedElasticSearchServiceStart { client: jest.Mocked; createClient: jest.Mock; } @@ -56,14 +58,11 @@ const createSetupContractMock = () => { const createStartContractMock = () => { const startContract: MockedElasticSearchServiceStart = { - client: elasticsearchClientMock.createClusterClient(), - createClient: jest.fn(), legacy: { createClient: jest.fn(), client: legacyClientMock.createClusterClient(), }, }; - startContract.createClient.mockReturnValue(elasticsearchClientMock.createCustomClusterClient()); startContract.legacy.createClient.mockReturnValue(legacyClientMock.createCustomClusterClient()); startContract.legacy.client.asScoped.mockReturnValue( legacyClientMock.createScopedClusterClient() @@ -71,6 +70,18 @@ const createStartContractMock = () => { return startContract; }; +const createInternalStartContractMock = () => { + const startContract: MockedInternalElasticSearchServiceStart = { + ...createStartContractMock(), + client: elasticsearchClientMock.createClusterClient(), + createClient: jest.fn(), + }; + + startContract.createClient.mockReturnValue(elasticsearchClientMock.createCustomClusterClient()); + + return startContract; +}; + type MockedInternalElasticSearchServiceSetup = jest.Mocked< InternalElasticsearchServiceSetup & { legacy: { client: jest.Mocked }; @@ -107,7 +118,7 @@ const createMock = () => { stop: jest.fn(), }; mocked.setup.mockResolvedValue(createInternalSetupContractMock()); - mocked.start.mockResolvedValueOnce(createStartContractMock()); + mocked.start.mockResolvedValueOnce(createInternalStartContractMock()); mocked.stop.mockResolvedValue(); return mocked; }; @@ -116,6 +127,7 @@ export const elasticsearchServiceMock = { create: createMock, createInternalSetup: createInternalSetupContractMock, createSetup: createSetupContractMock, + createInternalStart: createInternalStartContractMock, createStart: createStartContractMock, createLegacyClusterClient: legacyClientMock.createClusterClient, createLegacyCustomClusterClient: legacyClientMock.createCustomClusterClient, diff --git a/src/core/server/elasticsearch/elasticsearch_service.ts b/src/core/server/elasticsearch/elasticsearch_service.ts index 8fd5d0428f8cc..35e637675b5e2 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.ts @@ -32,7 +32,7 @@ import { import { ClusterClient, ICustomClusterClient, ElasticsearchClientConfig } from './client'; import { ElasticsearchConfig, ElasticsearchConfigType } from './elasticsearch_config'; import { InternalHttpServiceSetup, GetAuthHeaders } from '../http/'; -import { InternalElasticsearchServiceSetup, ElasticsearchServiceStart } from './types'; +import { InternalElasticsearchServiceSetup, InternalElasticsearchServiceStart } from './types'; import { pollEsNodesVersion } from './version_check/ensure_es_version'; import { calculateStatus$ } from './status'; @@ -42,13 +42,13 @@ interface SetupDeps { /** @internal */ export class ElasticsearchService - implements CoreService { + implements CoreService { private readonly log: Logger; private readonly config$: Observable; private stop$ = new Subject(); private kibanaVersion: string; - private createLegacyClient?: ( + private createLegacyCustomClient?: ( type: string, clientConfig?: Partial ) => ILegacyCustomClusterClient; @@ -83,7 +83,7 @@ export class ElasticsearchService kibanaVersion: this.kibanaVersion, }).pipe(takeUntil(this.stop$), shareReplay({ refCount: true, bufferSize: 1 })); - this.createLegacyClient = (type, clientConfig = {}) => { + this.createLegacyCustomClient = (type, clientConfig = {}) => { const finalConfig = merge({}, config, clientConfig); return this.createLegacyClusterClient(type, finalConfig, deps.http.getAuthHeaders); }; @@ -96,18 +96,18 @@ export class ElasticsearchService legacy: { config$: this.config$, client: this.legacyClient, - createClient: this.createLegacyClient, + createClient: this.createLegacyCustomClient, }, esNodesCompatibility$, status$: calculateStatus$(esNodesCompatibility$), }; } - public async start(): Promise { + public async start(): Promise { if ( !this.client || !this.createCustomClient || !this.legacyClient || - !this.createLegacyClient + !this.createLegacyCustomClient ) { throw new Error('ElasticsearchService needs to be setup before calling start'); } else { @@ -116,7 +116,7 @@ export class ElasticsearchService createClient: this.createCustomClient, legacy: { client: this.legacyClient, - createClient: this.createLegacyClient, + createClient: this.createLegacyCustomClient, }, }; } diff --git a/src/core/server/elasticsearch/index.ts b/src/core/server/elasticsearch/index.ts index 98298edfb594f..4392aa61d2657 100644 --- a/src/core/server/elasticsearch/index.ts +++ b/src/core/server/elasticsearch/index.ts @@ -25,6 +25,7 @@ export { ElasticsearchServiceStart, ElasticsearchStatusMeta, InternalElasticsearchServiceSetup, + InternalElasticsearchServiceStart, FakeRequest, ScopeableRequest, } from './types'; diff --git a/src/core/server/elasticsearch/types.ts b/src/core/server/elasticsearch/types.ts index a78447a381dc0..40399aecbc446 100644 --- a/src/core/server/elasticsearch/types.ts +++ b/src/core/server/elasticsearch/types.ts @@ -81,41 +81,20 @@ export interface ElasticsearchServiceSetup { }; } +/** @internal */ +export interface InternalElasticsearchServiceSetup { + // Required for the BWC with the legacy Kibana only. + readonly legacy: ElasticsearchServiceSetup['legacy'] & { + readonly config$: Observable; + }; + esNodesCompatibility$: Observable; + status$: Observable>; +} + /** * @public */ export interface ElasticsearchServiceStart { - /** - * A pre-configured {@link IClusterClient | Elasticsearch client} - * - * @example - * ```js - * const client = core.elasticsearch.client; - * ``` - */ - readonly client: IClusterClient; - /** - * Create application specific Elasticsearch cluster API client with customized config. See {@link IClusterClient}. - * - * @param type Unique identifier of the client - * @param clientConfig A config consists of Elasticsearch JS client options and - * valid sub-set of Elasticsearch service config. - * We fill all the missing properties in the `clientConfig` using the default - * Elasticsearch config so that we don't depend on default values set and - * controlled by underlying Elasticsearch JS client. - * We don't run validation against the passed config and expect it to be valid. - * - * @example - * ```js - * const client = elasticsearch.createClient('my-app-name', config); - * const data = await client.asInternalUser().search(); - * ``` - */ - readonly createClient: ( - type: string, - clientConfig?: Partial - ) => ICustomClusterClient; - /** * @deprecated * Provided for the backward compatibility. @@ -156,14 +135,40 @@ export interface ElasticsearchServiceStart { }; } -/** @internal */ -export interface InternalElasticsearchServiceSetup { - // Required for the BWC with the legacy Kibana only. - readonly legacy: ElasticsearchServiceSetup['legacy'] & { - readonly config$: Observable; - }; - esNodesCompatibility$: Observable; - status$: Observable>; +/** + * @internal + */ +export interface InternalElasticsearchServiceStart extends ElasticsearchServiceStart { + /** + * A pre-configured {@link IClusterClient | Elasticsearch client} + * + * @example + * ```js + * const client = core.elasticsearch.client; + * ``` + */ + readonly client: IClusterClient; + /** + * Create application specific Elasticsearch cluster API client with customized config. See {@link IClusterClient}. + * + * @param type Unique identifier of the client + * @param clientConfig A config consists of Elasticsearch JS client options and + * valid sub-set of Elasticsearch service config. + * We fill all the missing properties in the `clientConfig` using the default + * Elasticsearch config so that we don't depend on default values set and + * controlled by underlying Elasticsearch JS client. + * We don't run validation against the passed config and expect it to be valid. + * + * @example + * ```js + * const client = elasticsearch.createClient('my-app-name', config); + * const data = await client.asInternalUser().search(); + * ``` + */ + readonly createClient: ( + type: string, + clientConfig?: Partial + ) => ICustomClusterClient; } /** @public */ diff --git a/src/core/server/index.ts b/src/core/server/index.ts index 50a9b853dfc83..35aabab4a0b26 100644 --- a/src/core/server/index.ts +++ b/src/core/server/index.ts @@ -107,11 +107,6 @@ export { LegacyAPICaller, FakeRequest, ScopeableRequest, - IClusterClient, - ICustomClusterClient, - ElasticsearchClientConfig, - ClientFacade, - IScopedClusterClient, } from './elasticsearch'; export * from './elasticsearch/legacy/api_types'; export { diff --git a/src/core/server/internal_types.ts b/src/core/server/internal_types.ts index f6c17c2379862..8b5a87c0ffe61 100644 --- a/src/core/server/internal_types.ts +++ b/src/core/server/internal_types.ts @@ -22,7 +22,10 @@ import { Type } from '@kbn/config-schema'; import { CapabilitiesSetup, CapabilitiesStart } from './capabilities'; import { ConfigDeprecationProvider } from './config'; import { ContextSetup } from './context'; -import { InternalElasticsearchServiceSetup, ElasticsearchServiceStart } from './elasticsearch'; +import { + InternalElasticsearchServiceSetup, + InternalElasticsearchServiceStart, +} from './elasticsearch'; import { InternalHttpServiceSetup, InternalHttpServiceStart } from './http'; import { InternalSavedObjectsServiceSetup, @@ -56,7 +59,7 @@ export interface InternalCoreSetup { */ export interface InternalCoreStart { capabilities: CapabilitiesStart; - elasticsearch: ElasticsearchServiceStart; + elasticsearch: InternalElasticsearchServiceStart; http: InternalHttpServiceStart; metrics: InternalMetricsServiceStart; savedObjects: InternalSavedObjectsServiceStart; diff --git a/src/core/server/mocks.ts b/src/core/server/mocks.ts index 73d8e79069ce3..3c8d50d7b2d4f 100644 --- a/src/core/server/mocks.ts +++ b/src/core/server/mocks.ts @@ -173,7 +173,7 @@ function createInternalCoreSetupMock() { function createInternalCoreStartMock() { const startDeps: InternalCoreStart = { capabilities: capabilitiesServiceMock.createStartContract(), - elasticsearch: elasticsearchServiceMock.createStart(), + elasticsearch: elasticsearchServiceMock.createInternalStart(), http: httpServiceMock.createInternalStartContract(), metrics: metricsServiceMock.createStartContract(), savedObjects: savedObjectsServiceMock.createInternalStartContract(), diff --git a/src/core/server/plugins/plugin_context.ts b/src/core/server/plugins/plugin_context.ts index 4643789d99a88..77ea71dacbfae 100644 --- a/src/core/server/plugins/plugin_context.ts +++ b/src/core/server/plugins/plugin_context.ts @@ -209,7 +209,9 @@ export function createPluginStartContext( capabilities: { resolveCapabilities: deps.capabilities.resolveCapabilities, }, - elasticsearch: deps.elasticsearch, + elasticsearch: { + legacy: deps.elasticsearch.legacy, + }, http: { auth: deps.http.auth, basePath: deps.http.basePath, From 8cd1ed2269fafb6f68036d10675dcb40747d06d5 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 1 Jul 2020 13:23:03 +0200 Subject: [PATCH 27/42] revert using the new client for es version check --- .../elasticsearch_service.test.ts | 24 +++---- .../elasticsearch/elasticsearch_service.ts | 2 +- .../version_check/ensure_es_version.test.ts | 71 +++++++------------ .../version_check/ensure_es_version.ts | 17 +++-- 4 files changed, 42 insertions(+), 72 deletions(-) diff --git a/src/core/server/elasticsearch/elasticsearch_service.test.ts b/src/core/server/elasticsearch/elasticsearch_service.test.ts index e50f7cc7f74c5..7145c5e83d2a4 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.test.ts @@ -222,32 +222,28 @@ describe('#setup', () => { }); it('esNodeVersionCompatibility$ only starts polling when subscribed to', async (done) => { - const mockedClient = elasticsearchClientMock.createFacade(); - mockedClient.nodes.info.mockRejectedValue(new Error()); - mockClusterClientInstance.asInternalUser.mockReturnValue(mockedClient); + mockLegacyClusterClientInstance.callAsInternalUser.mockRejectedValue(new Error()); const setupContract = await elasticsearchService.setup(deps); await delay(10); - expect(mockedClient.nodes.info).toHaveBeenCalledTimes(0); + expect(mockLegacyClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(0); setupContract.esNodesCompatibility$.subscribe(() => { - expect(mockedClient.nodes.info).toHaveBeenCalledTimes(1); + expect(mockLegacyClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(1); done(); }); }); it('esNodeVersionCompatibility$ stops polling when unsubscribed from', async (done) => { - const mockedClient = elasticsearchClientMock.createFacade(); - mockedClient.nodes.info.mockRejectedValue(new Error()); - mockClusterClientInstance.asInternalUser.mockReturnValue(mockedClient); + mockLegacyClusterClientInstance.callAsInternalUser.mockRejectedValue(new Error()); const setupContract = await elasticsearchService.setup(deps); - expect(mockedClient.nodes.info).toHaveBeenCalledTimes(0); + expect(mockLegacyClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(0); const sub = setupContract.esNodesCompatibility$.subscribe(async () => { sub.unsubscribe(); await delay(100); - expect(mockedClient.nodes.info).toHaveBeenCalledTimes(1); + expect(mockLegacyClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(1); done(); }); }); @@ -265,18 +261,16 @@ describe('#stop', () => { it('stops pollEsNodeVersions even if there are active subscriptions', async (done) => { expect.assertions(2); - const mockedClient = elasticsearchClientMock.createFacade(); - mockedClient.nodes.info.mockRejectedValue(new Error()); - mockClusterClientInstance.asInternalUser.mockReturnValue(mockedClient); + mockLegacyClusterClientInstance.callAsInternalUser.mockRejectedValue(new Error()); const setupContract = await elasticsearchService.setup(deps); setupContract.esNodesCompatibility$.subscribe(async () => { - expect(mockedClient.nodes.info).toHaveBeenCalledTimes(1); + expect(mockLegacyClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(1); await elasticsearchService.stop(); await delay(100); - expect(mockedClient.nodes.info).toHaveBeenCalledTimes(1); + expect(mockLegacyClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(1); done(); }); }); diff --git a/src/core/server/elasticsearch/elasticsearch_service.ts b/src/core/server/elasticsearch/elasticsearch_service.ts index 35e637675b5e2..c4c2f63a8d392 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.ts @@ -76,7 +76,7 @@ export class ElasticsearchService this.legacyClient = this.createLegacyClusterClient('data', config, deps.http.getAuthHeaders); const esNodesCompatibility$ = pollEsNodesVersion({ - internalClient: this.client.asInternalUser(), + callWithInternalUser: this.legacyClient.callAsInternalUser, log: this.log, ignoreVersionMismatch: config.ignoreVersionMismatch, esVersionCheckInterval: config.healthCheckDelay.asMilliseconds(), diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts index 02a018f415307..3d1218d4a8e8b 100644 --- a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts +++ b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts @@ -18,7 +18,6 @@ */ import { mapNodesVersionCompatibility, pollEsNodesVersion, NodesInfo } from './ensure_es_version'; import { loggingSystemMock } from '../../logging/logging_system.mock'; -import { elasticsearchClientMock } from '../client/mocks'; import { take, delay } from 'rxjs/operators'; import { TestScheduler } from 'rxjs/testing'; import { of } from 'rxjs'; @@ -28,9 +27,6 @@ const mockLogger = mockLoggerFactory.get('mock logger'); const KIBANA_VERSION = '5.1.0'; -const createEsSuccess = elasticsearchClientMock.createClientResponse; -const createEsError = elasticsearchClientMock.createClientError; - function createNodes(...versions: string[]): NodesInfo { const nodes = {} as any; versions @@ -115,34 +111,25 @@ describe('mapNodesVersionCompatibility', () => { }); describe('pollEsNodesVersion', () => { - let internalClient: ReturnType; + const callWithInternalUser = jest.fn(); const getTestScheduler = () => new TestScheduler((actual, expected) => { expect(actual).toEqual(expected); }); beforeEach(() => { - internalClient = elasticsearchClientMock.createFacade(); + callWithInternalUser.mockReset(); }); - const nodeInfosSuccessOnce = (infos: NodesInfo) => { - internalClient.nodes.info.mockImplementationOnce(() => createEsSuccess(infos)); - }; - const nodeInfosErrorOnce = (error: any) => { - internalClient.nodes.info.mockImplementationOnce(() => createEsError(error)); - }; - it('returns iscCompatible=false and keeps polling when a poll request throws', (done) => { expect.assertions(3); const expectedCompatibilityResults = [false, false, true]; jest.clearAllMocks(); - - nodeInfosSuccessOnce(createNodes('5.1.0', '5.2.0', '5.0.0')); - nodeInfosErrorOnce('mock request error'); - nodeInfosSuccessOnce(createNodes('5.1.0', '5.2.0', '5.1.1-Beta1')); - + callWithInternalUser.mockResolvedValueOnce(createNodes('5.1.0', '5.2.0', '5.0.0')); + callWithInternalUser.mockRejectedValueOnce(new Error('mock request error')); + callWithInternalUser.mockResolvedValueOnce(createNodes('5.1.0', '5.2.0', '5.1.1-Beta1')); pollEsNodesVersion({ - internalClient, + callWithInternalUser, esVersionCheckInterval: 1, ignoreVersionMismatch: false, kibanaVersion: KIBANA_VERSION, @@ -161,11 +148,9 @@ describe('pollEsNodesVersion', () => { it('returns compatibility results', (done) => { expect.assertions(1); const nodes = createNodes('5.1.0', '5.2.0', '5.0.0'); - - nodeInfosSuccessOnce(nodes); - + callWithInternalUser.mockResolvedValueOnce(nodes); pollEsNodesVersion({ - internalClient, + callWithInternalUser, esVersionCheckInterval: 1, ignoreVersionMismatch: false, kibanaVersion: KIBANA_VERSION, @@ -183,15 +168,15 @@ describe('pollEsNodesVersion', () => { it('only emits if the node versions changed since the previous poll', (done) => { expect.assertions(4); - nodeInfosSuccessOnce(createNodes('5.1.0', '5.2.0', '5.0.0')); // emit - nodeInfosSuccessOnce(createNodes('5.0.0', '5.1.0', '5.2.0')); // ignore, same versions, different ordering - nodeInfosSuccessOnce(createNodes('5.1.1', '5.2.0', '5.0.0')); // emit - nodeInfosSuccessOnce(createNodes('5.1.1', '5.1.2', '5.1.3')); // emit - nodeInfosSuccessOnce(createNodes('5.1.1', '5.1.2', '5.1.3')); // ignore - nodeInfosSuccessOnce(createNodes('5.0.0', '5.1.0', '5.2.0')); // emit, different from previous version + callWithInternalUser.mockResolvedValueOnce(createNodes('5.1.0', '5.2.0', '5.0.0')); // emit + callWithInternalUser.mockResolvedValueOnce(createNodes('5.0.0', '5.1.0', '5.2.0')); // ignore, same versions, different ordering + callWithInternalUser.mockResolvedValueOnce(createNodes('5.1.1', '5.2.0', '5.0.0')); // emit + callWithInternalUser.mockResolvedValueOnce(createNodes('5.1.1', '5.1.2', '5.1.3')); // emit + callWithInternalUser.mockResolvedValueOnce(createNodes('5.1.1', '5.1.2', '5.1.3')); // ignore + callWithInternalUser.mockResolvedValueOnce(createNodes('5.0.0', '5.1.0', '5.2.0')); // emit, different from previous version pollEsNodesVersion({ - internalClient, + callWithInternalUser, esVersionCheckInterval: 1, ignoreVersionMismatch: false, kibanaVersion: KIBANA_VERSION, @@ -207,20 +192,14 @@ describe('pollEsNodesVersion', () => { it('starts polling immediately and then every esVersionCheckInterval', () => { expect.assertions(1); - // @ts-expect-error we need to return an incompatible type to use the testScheduler here - internalClient.nodes.info.mockReturnValueOnce([ - { body: createNodes('5.1.0', '5.2.0', '5.0.0') }, - ]); - // @ts-expect-error we need to return an incompatible type to use the testScheduler here - internalClient.nodes.info.mockReturnValueOnce([ - { body: createNodes('5.1.1', '5.2.0', '5.0.0') }, - ]); + callWithInternalUser.mockReturnValueOnce([createNodes('5.1.0', '5.2.0', '5.0.0')]); + callWithInternalUser.mockReturnValueOnce([createNodes('5.1.1', '5.2.0', '5.0.0')]); getTestScheduler().run(({ expectObservable }) => { const expected = 'a 99ms (b|)'; const esNodesCompatibility$ = pollEsNodesVersion({ - internalClient, + callWithInternalUser, esVersionCheckInterval: 100, ignoreVersionMismatch: false, kibanaVersion: KIBANA_VERSION, @@ -248,17 +227,15 @@ describe('pollEsNodesVersion', () => { getTestScheduler().run(({ expectObservable }) => { const expected = '100ms a 99ms (b|)'; - internalClient.nodes.info.mockReturnValueOnce( - // @ts-expect-error we need to return an incompatible type to use the testScheduler here - of({ body: createNodes('5.1.0', '5.2.0', '5.0.0') }).pipe(delay(100)) + callWithInternalUser.mockReturnValueOnce( + of(createNodes('5.1.0', '5.2.0', '5.0.0')).pipe(delay(100)) ); - internalClient.nodes.info.mockReturnValueOnce( - // @ts-expect-error we need to return an incompatible type to use the testScheduler here - of({ body: createNodes('5.1.1', '5.2.0', '5.0.0') }).pipe(delay(100)) + callWithInternalUser.mockReturnValueOnce( + of(createNodes('5.1.1', '5.2.0', '5.0.0')).pipe(delay(100)) ); const esNodesCompatibility$ = pollEsNodesVersion({ - internalClient, + callWithInternalUser, esVersionCheckInterval: 10, ignoreVersionMismatch: false, kibanaVersion: KIBANA_VERSION, @@ -279,6 +256,6 @@ describe('pollEsNodesVersion', () => { }); }); - expect(internalClient.nodes.info).toHaveBeenCalledTimes(2); + expect(callWithInternalUser).toHaveBeenCalledTimes(2); }); }); diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.ts index 6293bbabc23d0..dc56d982d7b4a 100644 --- a/src/core/server/elasticsearch/version_check/ensure_es_version.ts +++ b/src/core/server/elasticsearch/version_check/ensure_es_version.ts @@ -29,10 +29,10 @@ import { esVersionEqualsKibana, } from './es_kibana_version_compatability'; import { Logger } from '../../logging'; -import { ClientFacade } from '../client'; +import { LegacyAPICaller } from '../legacy'; export interface PollEsNodesVersionOptions { - internalClient: ClientFacade; + callWithInternalUser: LegacyAPICaller; log: Logger; kibanaVersion: string; ignoreVersionMismatch: boolean; @@ -137,7 +137,7 @@ function compareNodes(prev: NodesVersionCompatibility, curr: NodesVersionCompati } export const pollEsNodesVersion = ({ - internalClient, + callWithInternalUser, log, kibanaVersion, ignoreVersionMismatch, @@ -147,19 +147,18 @@ export const pollEsNodesVersion = ({ return timer(0, healthCheckInterval).pipe( exhaustMap(() => { return from( - internalClient.nodes.info({ - filter_path: ['nodes.*.version', 'nodes.*.http.publish_address', 'nodes.*.ip'], + callWithInternalUser('nodes.info', { + filterPath: ['nodes.*.version', 'nodes.*.http.publish_address', 'nodes.*.ip'], }) ).pipe( - map((response) => response.body), catchError((_err) => { return of({ nodes: {} }); }) ); }), - map((nodesInfo: NodesInfo) => { - return mapNodesVersionCompatibility(nodesInfo, kibanaVersion, ignoreVersionMismatch); - }), + map((nodesInfo: NodesInfo) => + mapNodesVersionCompatibility(nodesInfo, kibanaVersion, ignoreVersionMismatch) + ), distinctUntilChanged(compareNodes) // Only emit if there are new nodes or versions ); }; From 205c10050db6edf2cd3d5ad12d784ea38a1c78e1 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 1 Jul 2020 13:41:43 +0200 Subject: [PATCH 28/42] add service level test for new client --- .../elasticsearch_service.test.ts | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/src/core/server/elasticsearch/elasticsearch_service.test.ts b/src/core/server/elasticsearch/elasticsearch_service.test.ts index 7145c5e83d2a4..be2f83292525e 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.test.ts @@ -249,6 +249,94 @@ describe('#setup', () => { }); }); +describe('#start', () => { + it('throws if called before `setup`', async () => { + expect(() => elasticsearchService.start()).rejects.toMatchInlineSnapshot( + `[Error: ElasticsearchService needs to be setup before calling start]` + ); + }); + + it('returns elasticsearch client as a part of the contract', async () => { + await elasticsearchService.setup(deps); + const startContract = await elasticsearchService.start(); + const client = startContract.client; + + expect(client.asInternalUser).toHaveBeenCalledTimes(0); + client.asInternalUser(); + expect(mockClusterClientInstance.asInternalUser).toHaveBeenCalledTimes(1); + }); + + describe('#createClient', () => { + it('allows to specify config properties', async () => { + await elasticsearchService.setup(deps); + const startContract = await elasticsearchService.start(); + + // reset all mocks called during setup phase + MockClusterClient.mockClear(); + + const customConfig = { logQueries: true }; + const clusterClient = startContract.createClient('custom-type', customConfig); + + expect(clusterClient).toBe(mockClusterClientInstance); + + expect(MockClusterClient).toHaveBeenCalledTimes(1); + expect(MockClusterClient).toHaveBeenCalledWith( + expect.objectContaining(customConfig), + expect.objectContaining({ context: ['elasticsearch', 'custom-type'] }), + expect.any(Function) + ); + }); + it('creates a new client on each call', async () => { + await elasticsearchService.setup(deps); + const startContract = await elasticsearchService.start(); + + // reset all mocks called during setup phase + MockClusterClient.mockClear(); + + const customConfig = { logQueries: true }; + + startContract.createClient('custom-type', customConfig); + startContract.createClient('another-type', customConfig); + + expect(MockClusterClient).toHaveBeenCalledTimes(2); + }); + + it('falls back to elasticsearch default config values if property not specified', async () => { + await elasticsearchService.setup(deps); + const startContract = await elasticsearchService.start(); + + // reset all mocks called during setup phase + MockClusterClient.mockClear(); + + const customConfig = { + hosts: ['http://8.8.8.8'], + logQueries: true, + ssl: { certificate: 'certificate-value' }, + }; + + startContract.createClient('some-custom-type', customConfig); + const config = MockClusterClient.mock.calls[0][0]; + + expect(config).toMatchInlineSnapshot(` + Object { + "healthCheckDelay": "PT0.01S", + "hosts": Array [ + "http://8.8.8.8", + ], + "logQueries": true, + "requestHeadersWhitelist": Array [ + undefined, + ], + "ssl": Object { + "certificate": "certificate-value", + "verificationMode": "none", + }, + } + `); + }); + }); +}); + describe('#stop', () => { it('stops both legacy and new clients', async () => { await elasticsearchService.setup(deps); From 7819166c1007eb33ffd45abd8ee5ab70605a589c Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 1 Jul 2020 13:49:41 +0200 Subject: [PATCH 29/42] update generated API --- src/core/server/server.api.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index 9cc5a8a386b0b..da58c1129a6e1 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -4,6 +4,7 @@ ```ts +import { ApiResponse } from '@elastic/elasticsearch'; import Boom from 'boom'; import { BulkIndexDocumentsParams } from 'elasticsearch'; import { CatAliasesParams } from 'elasticsearch'; @@ -21,6 +22,7 @@ import { CatTasksParams } from 'elasticsearch'; import { CatThreadPoolParams } from 'elasticsearch'; import { ClearScrollParams } from 'elasticsearch'; import { Client } from 'elasticsearch'; +import { ClientOptions } from '@elastic/elasticsearch'; import { ClusterAllocationExplainParams } from 'elasticsearch'; import { ClusterGetSettingsParams } from 'elasticsearch'; import { ClusterHealthParams } from 'elasticsearch'; @@ -113,6 +115,9 @@ import { ReindexParams } from 'elasticsearch'; import { ReindexRethrottleParams } from 'elasticsearch'; import { RenderSearchTemplateParams } from 'elasticsearch'; import { Request } from 'hapi'; +import { RequestBody } from '@elastic/elasticsearch/lib/Transport'; +import { RequestNDBody } from '@elastic/elasticsearch/lib/Transport'; +import * as RequestParams from '@elastic/elasticsearch/api/requestParams'; import { ResponseObject } from 'hapi'; import { ResponseToolkit } from 'hapi'; import { SchemaTypeError } from '@kbn/config-schema'; @@ -138,6 +143,9 @@ import { TasksCancelParams } from 'elasticsearch'; import { TasksGetParams } from 'elasticsearch'; import { TasksListParams } from 'elasticsearch'; import { TermvectorsParams } from 'elasticsearch'; +import { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport'; +import { TransportRequestParams } from '@elastic/elasticsearch/lib/Transport'; +import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport'; import { Type } from '@kbn/config-schema'; import { TypeOf } from '@kbn/config-schema'; import { UpdateDocumentByQueryParams } from 'elasticsearch'; From bf18e61b219e4ceeaec1600ac09c0ad89479ecd9 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 1 Jul 2020 15:37:32 +0200 Subject: [PATCH 30/42] Revert "rename legacy client mocks" This reverts commit e48f3ad6 --- .../elasticsearch_service.mock.ts | 8 ++--- .../elasticsearch_service.test.ts | 4 +-- .../core_service.test.mocks.ts | 4 +-- src/core/server/mocks.ts | 2 +- .../actions/server/actions_client.test.ts | 2 +- x-pack/plugins/actions/server/mocks.ts | 2 +- x-pack/plugins/alerts/server/mocks.ts | 2 +- .../server/routes/_mock_handler_arguments.ts | 2 +- .../alerts/server/routes/health.test.ts | 14 ++++---- .../server/routes/es_fields/es_fields.test.ts | 4 +-- .../server/es/cluster_client_adapter.test.ts | 2 +- .../event_log/server/es/context.test.ts | 2 +- .../plugins/licensing/server/plugin.test.ts | 33 +++++++++---------- .../oss_telemetry/server/test_utils/index.ts | 2 +- .../server/routes/api/add_route.test.ts | 6 ++-- .../server/routes/api/delete_route.test.ts | 6 ++-- .../server/routes/api/get_route.test.ts | 6 ++-- .../server/routes/api/update_route.test.ts | 6 ++-- .../server/authentication/api_keys.test.ts | 4 +-- .../authentication/authenticator.test.ts | 2 +- .../server/authentication/index.test.ts | 4 +-- .../authentication/providers/base.mock.ts | 2 +- .../authentication/providers/basic.test.ts | 8 ++--- .../authentication/providers/http.test.ts | 4 +-- .../authentication/providers/kerberos.test.ts | 28 ++++++++-------- .../authentication/providers/oidc.test.ts | 16 ++++----- .../authentication/providers/pki.test.ts | 18 +++++----- .../authentication/providers/saml.test.ts | 30 ++++++++--------- .../authentication/providers/token.test.ts | 24 +++++++------- .../server/authentication/tokens.test.ts | 2 +- .../authorization_service.test.ts | 6 ++-- .../authorization/check_privileges.test.ts | 8 ++--- .../register_privileges_with_cluster.test.ts | 2 +- x-pack/plugins/security/server/plugin.test.ts | 2 +- .../server/routes/api_keys/get.test.ts | 2 +- .../server/routes/api_keys/invalidate.test.ts | 2 +- .../server/routes/api_keys/privileges.test.ts | 2 +- .../routes/authorization/roles/delete.test.ts | 2 +- .../routes/authorization/roles/get.test.ts | 2 +- .../authorization/roles/get_all.test.ts | 2 +- .../routes/authorization/roles/put.test.ts | 2 +- .../security/server/routes/index.mock.ts | 2 +- .../server/routes/role_mapping/delete.test.ts | 2 +- .../routes/role_mapping/feature_check.test.ts | 2 +- .../server/routes/role_mapping/get.test.ts | 6 ++-- .../server/routes/role_mapping/post.test.ts | 2 +- .../routes/users/change_password.test.ts | 2 +- .../endpoint/alerts/handlers/alerts.test.ts | 4 +-- .../endpoint/routes/metadata/metadata.test.ts | 4 +-- .../routes/metadata/support/unenroll.test.ts | 8 ++--- .../endpoint/routes/policy/handlers.test.ts | 2 +- .../routes/__mocks__/request_context.ts | 2 +- .../server/lib/machine_learning/mocks.ts | 2 +- .../lib/es_deprecation_logging_apis.test.ts | 6 ++-- .../server/lib/es_migration_apis.test.ts | 2 +- .../lib/telemetry/usage_collector.test.ts | 2 +- .../server/routes/__mocks__/routes.mock.ts | 2 +- .../__tests__/get_monitor_status.test.ts | 2 +- 58 files changed, 164 insertions(+), 169 deletions(-) diff --git a/src/core/server/elasticsearch/elasticsearch_service.mock.ts b/src/core/server/elasticsearch/elasticsearch_service.mock.ts index c67f575525786..de2ab34456e52 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.mock.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.mock.ts @@ -129,8 +129,8 @@ export const elasticsearchServiceMock = { createSetup: createSetupContractMock, createInternalStart: createInternalStartContractMock, createStart: createStartContractMock, - createLegacyClusterClient: legacyClientMock.createClusterClient, - createLegacyCustomClusterClient: legacyClientMock.createCustomClusterClient, - createLegacyScopedClusterClient: legacyClientMock.createScopedClusterClient, - createLegacyElasticsearchClient: legacyClientMock.createElasticsearchClient, + createClusterClient: legacyClientMock.createClusterClient, + createCustomClusterClient: legacyClientMock.createCustomClusterClient, + createScopedClusterClient: legacyClientMock.createScopedClusterClient, + createElasticsearchClient: legacyClientMock.createElasticsearchClient, }; diff --git a/src/core/server/elasticsearch/elasticsearch_service.test.ts b/src/core/server/elasticsearch/elasticsearch_service.test.ts index be2f83292525e..48bc66ab1140b 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.test.ts @@ -59,7 +59,7 @@ let coreContext: CoreContext; const logger = loggingSystemMock.create(); let mockClusterClientInstance: ReturnType; -let mockLegacyClusterClientInstance: ReturnType; +let mockLegacyClusterClientInstance: ReturnType; beforeEach(() => { env = Env.createDefault(getEnvOptions()); @@ -70,7 +70,7 @@ beforeEach(() => { MockLegacyClusterClient.mockClear(); MockClusterClient.mockClear(); - mockLegacyClusterClientInstance = elasticsearchServiceMock.createLegacyCustomClusterClient(); + mockLegacyClusterClientInstance = elasticsearchServiceMock.createCustomClusterClient(); MockLegacyClusterClient.mockImplementation(() => mockLegacyClusterClientInstance); mockClusterClientInstance = elasticsearchClientMock.createCustomClusterClient(); MockClusterClient.mockImplementation(() => mockClusterClientInstance); 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 f7ebd18b9c488..6f9b4b96eae9d 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.createLegacyScopedClusterClient(); + return elasticsearchServiceMock.createScopedClusterClient(); }), })); @@ -31,7 +31,7 @@ jest.doMock('elasticsearch', () => { ...realES, // eslint-disable-next-line object-shorthand Client: function () { - return elasticsearchServiceMock.createLegacyElasticsearchClient(); + return elasticsearchServiceMock.createElasticsearchClient(); }, }; }); diff --git a/src/core/server/mocks.ts b/src/core/server/mocks.ts index 3c8d50d7b2d4f..5745724c71f9e 100644 --- a/src/core/server/mocks.ts +++ b/src/core/server/mocks.ts @@ -190,7 +190,7 @@ function createCoreRequestHandlerContextMock() { }, elasticsearch: { legacy: { - client: elasticsearchServiceMock.createLegacyScopedClusterClient(), + client: elasticsearchServiceMock.createScopedClusterClient(), }, }, uiSettings: { diff --git a/x-pack/plugins/actions/server/actions_client.test.ts b/x-pack/plugins/actions/server/actions_client.test.ts index 807d75cd0d701..69fab828e63de 100644 --- a/x-pack/plugins/actions/server/actions_client.test.ts +++ b/x-pack/plugins/actions/server/actions_client.test.ts @@ -25,7 +25,7 @@ import { KibanaRequest } from 'kibana/server'; const defaultKibanaIndex = '.kibana'; const savedObjectsClient = savedObjectsClientMock.create(); -const scopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); +const scopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); const actionExecutor = actionExecutorMock.create(); const executionEnqueuer = jest.fn(); const request = {} as KibanaRequest; diff --git a/x-pack/plugins/actions/server/mocks.ts b/x-pack/plugins/actions/server/mocks.ts index 87aa571ce6b8a..1763d275c6fb0 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.createLegacyScopedClusterClient().callAsCurrentUser, + callCluster: elasticsearchServiceMock.createScopedClusterClient().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 84f79d53f218c..c94a7aba46cfa 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.createLegacyScopedClusterClient().callAsCurrentUser, + callCluster: elasticsearchServiceMock.createScopedClusterClient().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 548495866ec21..7d86d4fde7e61 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.createLegacyClusterClient(), + esClient = elasticsearchServiceMock.createClusterClient(), }: { 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 ce782dbd631a5..b3f41e03ebdc9 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.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); 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.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); 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.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); 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.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); 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.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); 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.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); 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.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); esClient.callAsInternalUser.mockReturnValue( Promise.resolve({ security: { enabled: true, ssl: { http: { enabled: true } } } }) ); 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 c2cff83f85f0d..c1918feb7f4ec 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,9 +15,7 @@ import { const mockRouteContext = ({ core: { - elasticsearch: { - legacy: { client: elasticsearchServiceMock.createLegacyScopedClusterClient() }, - }, + elasticsearch: { legacy: { client: elasticsearchServiceMock.createScopedClusterClient() } }, }, } 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 ee6f0a301e9f8..feec1ee9ba008 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.createLegacyClusterClient(); + clusterClient = elasticsearchServiceMock.createClusterClient(); 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 a78e47446fef8..3fd7e12ed8a0c 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.createLegacyClusterClient(); + clusterClient = elasticsearchServiceMock.createClusterClient(); }); describe('createEsContext', () => { diff --git a/x-pack/plugins/licensing/server/plugin.test.ts b/x-pack/plugins/licensing/server/plugin.test.ts index 6e8327e151543..bf549c18da303 100644 --- a/x-pack/plugins/licensing/server/plugin.test.ts +++ b/x-pack/plugins/licensing/server/plugin.test.ts @@ -31,14 +31,11 @@ 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([ { - ...coreStart, - elasticsearch: { - ...coreStart.elasticsearch, - legacy: { client: esClient, createClient: jest.fn() }, - }, + ...coreMock.createStart(), + elasticsearch: { legacy: { client: esClient, createClient: jest.fn() } }, }, {}, {}, @@ -64,7 +61,7 @@ describe('licensing plugin', () => { }); it('returns license', async () => { - const esClient = elasticsearchServiceMock.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); esClient.callAsInternalUser.mockResolvedValue({ license: buildRawLicense(), features: {}, @@ -80,7 +77,7 @@ describe('licensing plugin', () => { it('observable receives updated licenses', async () => { const types: LicenseType[] = ['basic', 'gold', 'platinum']; - const esClient = elasticsearchServiceMock.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); esClient.callAsInternalUser.mockImplementation(() => Promise.resolve({ license: buildRawLicense({ type: types.shift() }), @@ -99,7 +96,7 @@ describe('licensing plugin', () => { }); it('returns a license with error when request fails', async () => { - const esClient = elasticsearchServiceMock.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); esClient.callAsInternalUser.mockRejectedValue(new Error('test')); const coreSetup = createCoreSetupWith(esClient); @@ -112,7 +109,7 @@ describe('licensing plugin', () => { }); it('generate error message when x-pack plugin was not installed', async () => { - const esClient = elasticsearchServiceMock.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); const error: ElasticsearchError = new Error('reason'); error.status = 400; esClient.callAsInternalUser.mockRejectedValue(error); @@ -130,7 +127,7 @@ describe('licensing plugin', () => { const error1 = new Error('reason-1'); const error2 = new Error('reason-2'); - const esClient = elasticsearchServiceMock.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); esClient.callAsInternalUser .mockRejectedValueOnce(error1) @@ -148,7 +145,7 @@ describe('licensing plugin', () => { }); it('fetch license immediately without subscriptions', async () => { - const esClient = elasticsearchServiceMock.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); esClient.callAsInternalUser.mockResolvedValue({ license: buildRawLicense(), features: {}, @@ -164,7 +161,7 @@ describe('licensing plugin', () => { }); it('logs license details without subscriptions', async () => { - const esClient = elasticsearchServiceMock.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); esClient.callAsInternalUser.mockResolvedValue({ license: buildRawLicense(), features: {}, @@ -190,7 +187,7 @@ describe('licensing plugin', () => { it('generates signature based on fetched license content', async () => { const types: LicenseType[] = ['basic', 'gold', 'basic']; - const esClient = elasticsearchServiceMock.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); esClient.callAsInternalUser.mockImplementation(() => Promise.resolve({ license: buildRawLicense({ type: types.shift() }), @@ -221,7 +218,7 @@ describe('licensing plugin', () => { api_polling_frequency: moment.duration(50000), }) ); - const esClient = elasticsearchServiceMock.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); esClient.callAsInternalUser.mockResolvedValue({ license: buildRawLicense(), features: {}, @@ -256,7 +253,7 @@ describe('licensing plugin', () => { }) ); - const esClient = elasticsearchServiceMock.createLegacyClusterClient(); + const esClient = elasticsearchServiceMock.createClusterClient(); esClient.callAsInternalUser.mockResolvedValue({ license: buildRawLicense(), features: {}, @@ -265,7 +262,7 @@ describe('licensing plugin', () => { await plugin.setup(coreSetup); const { createLicensePoller, license$ } = await plugin.start(); - const customClient = elasticsearchServiceMock.createLegacyClusterClient(); + const customClient = elasticsearchServiceMock.createClusterClient(); customClient.callAsInternalUser.mockResolvedValue({ license: buildRawLicense({ type: 'gold' }), features: {}, @@ -300,7 +297,7 @@ describe('licensing plugin', () => { await plugin.setup(coreSetup); const { createLicensePoller } = await plugin.start(); - const customClient = elasticsearchServiceMock.createLegacyClusterClient(); + const customClient = elasticsearchServiceMock.createClusterClient(); customClient.callAsInternalUser.mockResolvedValue({ license: buildRawLicense({ type: 'gold' }), features: {}, 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 3eee1978d4f1c..7ac9819680839 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.createLegacyClusterClient(); + const client = elasticsearchServiceMock.createClusterClient(); (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 406d5661c0915..d28e95834ca0b 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.createLegacyClusterClient(); + const elasticsearchMock = elasticsearchServiceMock.createClusterClient(); const mockRouteDependencies = { router: httpServiceMock.createRouter(), @@ -40,10 +40,10 @@ describe('ADD remote clusters', () => { }, }; - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); elasticsearchServiceMock - .createLegacyClusterClient() + .createClusterClient() .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 bd2ad10c4013d..d1e3cf89e94d9 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.createLegacyClusterClient(); + const elasticsearchMock = elasticsearchServiceMock.createClusterClient(); const mockRouteDependencies = { router: httpServiceMock.createRouter(), @@ -42,10 +42,10 @@ describe('DELETE remote clusters', () => { }, }; - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); elasticsearchServiceMock - .createLegacyClusterClient() + .createClusterClient() .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 910f9e69ea80c..24e469c9ec9b2 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.createLegacyClusterClient(); + const elasticsearchMock = elasticsearchServiceMock.createClusterClient(); const mockRouteDependencies = { router: httpServiceMock.createRouter(), @@ -41,10 +41,10 @@ describe('GET remote clusters', () => { }, }; - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); elasticsearchServiceMock - .createLegacyClusterClient() + .createClusterClient() .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 c20ba0a1ec7a9..9669c98e1349e 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.createLegacyClusterClient(); + const elasticsearchMock = elasticsearchServiceMock.createClusterClient(); const mockRouteDependencies = { router: httpServiceMock.createRouter(), @@ -49,10 +49,10 @@ describe('UPDATE remote clusters', () => { }, }; - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); elasticsearchServiceMock - .createLegacyClusterClient() + .createClusterClient() .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 631a6f9ab213c..0cdd452d459d1 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.createLegacyClusterClient(); - mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + mockClusterClient = elasticsearchServiceMock.createClusterClient(); + mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 300447096af99..3b77ea3248173 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.createLegacyClusterClient(), + clusterClient: elasticsearchServiceMock.createClusterClient(), 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 56d44e6628a87..4157f0598b3d0 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.createLegacyClusterClient(), + clusterClient: elasticsearchServiceMock.createClusterClient(), license: licenseMock.create(), loggers: loggingSystemMock.create(), getFeatureUsageService: jest @@ -77,7 +77,7 @@ describe('setupAuthentication()', () => { .mockReturnValue(securityFeatureUsageServiceMock.createStartContract()), }; - mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 1b574e6e44c10..7c71348bb8ca0 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.createLegacyClusterClient(), + client: elasticsearchServiceMock.createClusterClient(), 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 22d10d1cec347..95de8ca9d00e7 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 c221ecd3f1e20..e6949269e3fc7 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 f04506eb01593..c00374efd59b4 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -82,7 +82,7 @@ describe('KerberosAuthenticationProvider', () => { body: { error: { header: { 'WWW-Authenticate': 'Negotiate' } } }, }) ); - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -118,7 +118,7 @@ describe('KerberosAuthenticationProvider', () => { headers: { authorization: 'negotiate spnego' }, }); - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -386,7 +386,7 @@ describe('KerberosAuthenticationProvider', () => { } if (scopeableRequest?.headers.authorization === 'Bearer newfoo') { - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); return mockScopedClusterClient; } @@ -423,7 +423,7 @@ describe('KerberosAuthenticationProvider', () => { }; const failureReason = new errors.InternalServerError('Token is not valid!'); - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -450,7 +450,7 @@ describe('KerberosAuthenticationProvider', () => { body: { error: { header: { 'WWW-Authenticate': 'Negotiate' } } }, }) ); - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -475,7 +475,7 @@ describe('KerberosAuthenticationProvider', () => { body: { error: { header: { 'WWW-Authenticate': 'Negotiate' } } }, }) ); - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 aea5994e3ba3e..d787e76628d6d 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -474,7 +474,7 @@ describe('OIDCAuthenticationProvider', () => { } if (scopeableRequest?.headers.authorization === 'Bearer new-access-token') { - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 fec03c5d04b0d..fd014e1a7cb81 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -480,7 +480,7 @@ describe('PKIAuthenticationProvider', () => { }), }); - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -509,7 +509,7 @@ describe('PKIAuthenticationProvider', () => { }); const failureReason = new errors.ServiceUnavailable(); - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 851ecf8107ad2..e9af806b36f04 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockImplementation(() => Promise.resolve(mockAuthenticatedUser()) ); @@ -448,7 +448,7 @@ describe('SAMLAuthenticationProvider', () => { const authorization = 'Bearer some-valid-token'; const user = mockAuthenticatedUser(); - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -543,7 +543,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockImplementation(() => response); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -598,7 +598,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockImplementation(() => response); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -663,7 +663,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockImplementation(() => response); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -1061,7 +1061,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -1121,7 +1121,7 @@ describe('SAMLAuthenticationProvider', () => { } if (scopeableRequest?.headers.authorization === 'Bearer new-access-token') { - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); return mockScopedClusterClient; } @@ -1165,7 +1165,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -1199,7 +1199,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -1231,7 +1231,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -1263,7 +1263,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 f83331d84e43c..ba0f23a3393ae 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -106,7 +106,7 @@ describe('TokenAuthenticationProvider', () => { }); const authenticationError = new Error('Some error'); - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -221,7 +221,7 @@ describe('TokenAuthenticationProvider', () => { } if (scopeableRequest?.headers.authorization === 'Bearer newfoo') { - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -397,7 +397,7 @@ describe('TokenAuthenticationProvider', () => { } if (scopeableRequest?.headers.authorization === 'Bearer newfoo') { - const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 e8cf37330aff2..8ad04672fdfad 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.createLegacyClusterClient(); + mockClusterClient = elasticsearchServiceMock.createClusterClient(); 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 f67e0863086bb..4d0ab1c964741 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.createLegacyClusterClient(); + const mockClusterClient = elasticsearchServiceMock.createClusterClient(); 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.createLegacyClusterClient(); + const mockClusterClient = elasticsearchServiceMock.createClusterClient(); 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.createLegacyClusterClient(); + const mockClusterClient = elasticsearchServiceMock.createClusterClient(); 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 364a5b737f2cf..cc46690a894d1 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(response); - const mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient(); + const mockClusterClient = elasticsearchServiceMock.createClusterClient(); 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 c102af76805b0..0ce7eae932fea 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.createLegacyClusterClient(); + const mockClusterClient = elasticsearchServiceMock.createClusterClient(); 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 a7b958ee02de5..64af6fc857273 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.createLegacyCustomClusterClient(); + mockClusterClient = elasticsearchServiceMock.createCustomClusterClient(); 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 40065e757e999..f77469552d980 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 33c52688ce8e3..2889cf78aff83 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 a506cc6306c53..afb67dc3bbfca 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 399f79f44744d..ada6a1c8d2dc3 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 d9062bcfa2efe..49123fe9c74d7 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 66e8086d49c66..5dbe8682c5426 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 8f115f11329d3..bec60fa149bcf 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 24de2af5e9703..c7ff2a1e68b02 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.createLegacyClusterClient(), + clusterClient: elasticsearchServiceMock.createClusterClient(), 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 aec0310129f6e..34961dbe27675 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 ee1d550bbe24d..8070b3371fcb3 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 9af7268a57f9c..e0df59ebe7a00 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 8f61d2a122f0c..ed3d1bbd0fca2 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.createLegacyScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); 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 21c7fc1340437..721c020c7431b 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.createLegacyScopedClusterClient(); + mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockClusterClient = routeParamsMock.clusterClient; mockClusterClient.asScoped.mockReturnValue(mockScopedClusterClient); diff --git a/x-pack/plugins/security_solution/server/endpoint/alerts/handlers/alerts.test.ts b/x-pack/plugins/security_solution/server/endpoint/alerts/handlers/alerts.test.ts index addfae4ed16cc..24af9917186ba 100644 --- a/x-pack/plugins/security_solution/server/endpoint/alerts/handlers/alerts.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/alerts/handlers/alerts.test.ts @@ -22,8 +22,8 @@ describe('test alerts route', () => { let endpointAppContextService: EndpointAppContextService; beforeEach(() => { - mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient(); - mockScopedClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + mockClusterClient = elasticsearchServiceMock.createClusterClient(); + mockScopedClient = elasticsearchServiceMock.createScopedClusterClient(); mockClusterClient.asScoped.mockReturnValue(mockScopedClient); routerMock = httpServiceMock.createRouter(); 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 310b9e7136a04..f6ae2c584a346 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', () => { } as unknown) as SearchResponse); beforeEach(() => { - mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient() as jest.Mocked< + mockClusterClient = elasticsearchServiceMock.createClusterClient() as jest.Mocked< ILegacyClusterClient >; - mockScopedClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + mockScopedClient = elasticsearchServiceMock.createScopedClusterClient(); mockSavedObjectClient = savedObjectsClientMock.create(); mockClusterClient.asScoped.mockReturnValue(mockScopedClient); routerMock = httpServiceMock.createRouter(); diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/unenroll.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/unenroll.test.ts index 8ea30315c6a8c..545095a6a0c16 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/unenroll.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/unenroll.test.ts @@ -29,7 +29,7 @@ describe('test find all unenrolled HostId', () => { it('can find all hits with scroll', async () => { const firstHostId = '1fdca33f-799f-49f4-939c-ea4383c77671'; const secondHostId = '2fdca33f-799f-49f4-939c-ea4383c77672'; - mockScopedClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + mockScopedClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClient.callAsCurrentUser .mockImplementationOnce(() => Promise.resolve(createSearchResponse(secondHostId, 'scrollId'))) .mockImplementationOnce(noUnenrolledEndpoint); @@ -46,7 +46,7 @@ describe('test find all unenrolled HostId', () => { it('can find all unerolled endpoint host ids', async () => { const firstEndpointHostId = '1fdca33f-799f-49f4-939c-ea4383c77671'; const secondEndpointHostId = '2fdca33f-799f-49f4-939c-ea4383c77672'; - mockScopedClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + mockScopedClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClient.callAsCurrentUser .mockImplementationOnce(() => Promise.resolve(createSearchResponse(firstEndpointHostId, 'initialScrollId')) @@ -86,7 +86,7 @@ describe('test find unenrolled endpoint host id by hostId', () => { it('can find unenrolled endpoint by the host id when unenrolled', async () => { const firstEndpointHostId = '1fdca33f-799f-49f4-939c-ea4383c77671'; - mockScopedClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + mockScopedClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClient.callAsCurrentUser.mockImplementationOnce(() => Promise.resolve(createSearchResponse(firstEndpointHostId, 'initialScrollId')) ); @@ -119,7 +119,7 @@ describe('test find unenrolled endpoint host id by hostId', () => { it('find unenrolled endpoint host by the host id return undefined when no unenrolled host', async () => { const firstHostId = '1fdca33f-799f-49f4-939c-ea4383c77671'; - mockScopedClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); + mockScopedClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClient.callAsCurrentUser.mockImplementationOnce(noUnenrolledEndpoint); const hostId = await findUnenrolledHostByHostId(mockScopedClient, firstHostId); expect(hostId).toBeFalsy(); 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 8d4524e06c49f..0578f795f4a4e 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.createLegacyScopedClusterClient(); + mockScopedClient = elasticsearchServiceMock.createScopedClusterClient(); 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 c45dd5bd8a281..7289eb6dea161 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.createLegacyScopedClusterClient(), + clusterClient: elasticsearchServiceMock.createScopedClusterClient(), 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 e9b692e4731aa..f044022d6db69 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.createLegacyClusterClient(); +const createMockClient = () => elasticsearchServiceMock.createClusterClient(); 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 b0dec299b2b12..4ce21f1b311e8 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.createLegacyScopedClusterClient(); + const dataClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const dataClient = elasticsearchServiceMock.createScopedClusterClient(); 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.createLegacyScopedClusterClient(); + const dataClient = elasticsearchServiceMock.createScopedClusterClient(); 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 2a4fa5cd48ded..89571a4a18231 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.createLegacyScopedClusterClient(); + const dataClient = elasticsearchServiceMock.createScopedClusterClient(); (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 e14056439ca6b..7188241e10f9a 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.createLegacyClusterClient(); + clusterClient = elasticsearchServiceMock.createClusterClient(); (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 2df770c3ce45c..861ef2d3968dc 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.createLegacyScopedClusterClient(), + client: elasticsearchServiceMock.createScopedClusterClient(), }, }, 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 2a1417b49dca4..17bbb051b1ab1 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.createLegacyScopedClusterClient(); + const esMock = elasticsearchServiceMock.createScopedClusterClient(); criteria.forEach(({ after_key, bucketCriteria }) => { const mockResponse = { From 8a397d006ef462238792071c1d555566ce39ecd1 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 1 Jul 2020 21:08:59 +0200 Subject: [PATCH 31/42] address some review comments --- .../client/client_config.test.ts | 174 ++++++++++-------- .../elasticsearch/client/configure_client.ts | 5 +- .../elasticsearch_service.test.ts | 1 + .../elasticsearch/elasticsearch_service.ts | 60 +++--- 4 files changed, 130 insertions(+), 110 deletions(-) diff --git a/src/core/server/elasticsearch/client/client_config.test.ts b/src/core/server/elasticsearch/client/client_config.test.ts index 8da0884899386..675d8840e7118 100644 --- a/src/core/server/elasticsearch/client/client_config.test.ts +++ b/src/core/server/elasticsearch/client/client_config.test.ts @@ -62,40 +62,62 @@ describe('parseClientOptions', () => { expect(parseClientOptions(createConfig({ keepAlive: false }), false).agent).toBeUndefined(); }); - it('`sniff` options', () => { + it('`sniffOnStart` options', () => { expect( parseClientOptions( createConfig({ sniffOnStart: true, - sniffOnConnectionFault: false, - sniffInterval: false, }), false - ) - ).toEqual( - expect.objectContaining({ - sniffOnStart: true, - sniffOnConnectionFault: false, - sniffInterval: false, - }) - ); + ).sniffOnStart + ).toEqual(true); expect( parseClientOptions( createConfig({ sniffOnStart: false, + }), + false + ).sniffOnStart + ).toEqual(false); + }); + it('`sniffOnConnectionFault` options', () => { + expect( + parseClientOptions( + createConfig({ sniffOnConnectionFault: true, + }), + false + ).sniffOnConnectionFault + ).toEqual(true); + + expect( + parseClientOptions( + createConfig({ + sniffOnConnectionFault: false, + }), + false + ).sniffOnConnectionFault + ).toEqual(false); + }); + it('`sniffInterval` options', () => { + expect( + parseClientOptions( + createConfig({ + sniffInterval: false, + }), + false + ).sniffInterval + ).toEqual(false); + + expect( + parseClientOptions( + createConfig({ sniffInterval: duration(100, 'ms'), }), false - ) - ).toEqual( - expect.objectContaining({ - sniffOnStart: false, - sniffOnConnectionFault: true, - sniffInterval: 100, - }) - ); + ).sniffInterval + ).toEqual(100); }); it('`hosts` option', () => { @@ -267,79 +289,85 @@ describe('parseClientOptions', () => { ).toEqual(['content-of-ca-path']); }); - it('handles the `verificationMode` option', () => { - expect( - parseClientOptions( - createConfig({ - ssl: { - verificationMode: 'none', - }, - }), - false - ).ssl - ).toMatchInlineSnapshot(` + describe('verificationMode', () => { + it('handles `none` value', () => { + expect( + parseClientOptions( + createConfig({ + ssl: { + verificationMode: 'none', + }, + }), + false + ).ssl + ).toMatchInlineSnapshot(` Object { "ca": undefined, "rejectUnauthorized": false, } `); - - expect( - parseClientOptions( - createConfig({ - ssl: { - verificationMode: 'certificate', - }, - }), - false - ).ssl - ).toMatchInlineSnapshot(` - Object { - "ca": undefined, - "checkServerIdentity": [Function], - "rejectUnauthorized": true, - } - `); - - expect( - parseClientOptions( - createConfig({ - ssl: { - verificationMode: 'full', - }, - }), - false - ).ssl - ).toMatchInlineSnapshot(` - Object { - "ca": undefined, - "rejectUnauthorized": true, - } - `); - - expect( - () => + }); + it('handles `certificate` value', () => { + expect( parseClientOptions( createConfig({ ssl: { - verificationMode: 'unknown' as any, + verificationMode: 'certificate', }, }), false ).ssl - ).toThrowErrorMatchingInlineSnapshot(`"Unknown ssl verificationMode: unknown"`); - - expect( - () => + ).toMatchInlineSnapshot(` + Object { + "ca": undefined, + "checkServerIdentity": [Function], + "rejectUnauthorized": true, + } + `); + }); + it('handles `full` value', () => { + expect( parseClientOptions( createConfig({ ssl: { - verificationMode: undefined as any, + verificationMode: 'full', }, }), false ).ssl - ).toThrowErrorMatchingInlineSnapshot(`"Unknown ssl verificationMode: undefined"`); + ).toMatchInlineSnapshot(` + Object { + "ca": undefined, + "rejectUnauthorized": true, + } + `); + }); + it('throws for invalid values', () => { + expect( + () => + parseClientOptions( + createConfig({ + ssl: { + verificationMode: 'unknown' as any, + }, + }), + false + ).ssl + ).toThrowErrorMatchingInlineSnapshot(`"Unknown ssl verificationMode: unknown"`); + }); + it('throws for undefined values', () => { + expect( + () => + parseClientOptions( + createConfig({ + ssl: { + verificationMode: undefined as any, + }, + }), + false + ).ssl + ).toThrowErrorMatchingInlineSnapshot(`"Unknown ssl verificationMode: undefined"`); + }); }); describe('`certificate`, `key` and `passphrase`', () => { diff --git a/src/core/server/elasticsearch/client/configure_client.ts b/src/core/server/elasticsearch/client/configure_client.ts index 91af3cd5edc6b..093c8363a8a16 100644 --- a/src/core/server/elasticsearch/client/configure_client.ts +++ b/src/core/server/elasticsearch/client/configure_client.ts @@ -17,6 +17,7 @@ * under the License. */ +import { stringify } from 'querystring'; import { Client } from '@elastic/elasticsearch'; import { Logger } from '../../logging'; import { parseClientOptions, ElasticsearchClientConfig } from './client_config'; @@ -59,7 +60,5 @@ const convertQueryString = (qs: string | Record | undefined): strin if (qs === undefined || typeof qs === 'string') { return qs ?? ''; } - return Object.entries(qs) - .map(([key, value]) => `${key}=${value}`) - .join('&'); + return stringify(qs); }; diff --git a/src/core/server/elasticsearch/elasticsearch_service.test.ts b/src/core/server/elasticsearch/elasticsearch_service.test.ts index 48bc66ab1140b..b0a76ee6e1509 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.test.ts @@ -340,6 +340,7 @@ describe('#start', () => { describe('#stop', () => { it('stops both legacy and new clients', async () => { await elasticsearchService.setup(deps); + await elasticsearchService.start(); await elasticsearchService.stop(); expect(mockLegacyClusterClientInstance.close).toHaveBeenCalledTimes(1); diff --git a/src/core/server/elasticsearch/elasticsearch_service.ts b/src/core/server/elasticsearch/elasticsearch_service.ts index c4c2f63a8d392..10fce9ec3c021 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.ts @@ -47,6 +47,7 @@ export class ElasticsearchService private readonly config$: Observable; private stop$ = new Subject(); private kibanaVersion: string; + private getAuthHeaders?: GetAuthHeaders; private createLegacyCustomClient?: ( type: string, @@ -72,8 +73,9 @@ export class ElasticsearchService this.log.debug('Setting up elasticsearch service'); const config = await this.config$.pipe(first()).toPromise(); - this.client = this.createClusterClient('data', config, deps.http.getAuthHeaders); - this.legacyClient = this.createLegacyClusterClient('data', config, deps.http.getAuthHeaders); + + this.getAuthHeaders = deps.http.getAuthHeaders; + this.legacyClient = this.createLegacyClusterClient('data', config); const esNodesCompatibility$ = pollEsNodesVersion({ callWithInternalUser: this.legacyClient.callAsInternalUser, @@ -85,11 +87,7 @@ export class ElasticsearchService this.createLegacyCustomClient = (type, clientConfig = {}) => { const finalConfig = merge({}, config, clientConfig); - return this.createLegacyClusterClient(type, finalConfig, deps.http.getAuthHeaders); - }; - this.createCustomClient = (type, clientConfig = {}) => { - const finalConfig = merge({}, config, clientConfig); - return this.createClusterClient(type, finalConfig, deps.http.getAuthHeaders); + return this.createLegacyClusterClient(type, finalConfig); }; return { @@ -103,23 +101,25 @@ export class ElasticsearchService }; } public async start(): Promise { - if ( - !this.client || - !this.createCustomClient || - !this.legacyClient || - !this.createLegacyCustomClient - ) { + if (!this.legacyClient || !this.createLegacyCustomClient) { throw new Error('ElasticsearchService needs to be setup before calling start'); - } else { - return { - client: this.client, - createClient: this.createCustomClient, - legacy: { - client: this.legacyClient, - createClient: this.createLegacyCustomClient, - }, - }; } + + const config = await this.config$.pipe(first()).toPromise(); + this.client = this.createClusterClient('data', config); + this.createCustomClient = (type, clientConfig = {}) => { + const finalConfig = merge({}, config, clientConfig); + return this.createClusterClient(type, finalConfig); + }; + + return { + client: this.client, + createClient: this.createCustomClient, + legacy: { + client: this.legacyClient, + createClient: this.createLegacyCustomClient, + }, + }; } public async stop() { @@ -133,27 +133,19 @@ export class ElasticsearchService } } - private createClusterClient( - type: string, - config: ElasticsearchClientConfig, - getAuthHeaders?: GetAuthHeaders - ) { + private createClusterClient(type: string, config: ElasticsearchClientConfig) { return new ClusterClient( config, this.coreContext.logger.get('elasticsearch', type), - getAuthHeaders + this.getAuthHeaders ); } - private createLegacyClusterClient( - type: string, - config: LegacyElasticsearchClientConfig, - getAuthHeaders?: GetAuthHeaders - ) { + private createLegacyClusterClient(type: string, config: LegacyElasticsearchClientConfig) { return new LegacyClusterClient( config, this.coreContext.logger.get('elasticsearch', type), - getAuthHeaders + this.getAuthHeaders ); } } From 0a09aee0a519f8daf42f4d27f0aa776a9e4b3051 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 2 Jul 2020 09:17:48 +0200 Subject: [PATCH 32/42] revert ts-expect-error from unowned files --- .../security/server/authorization/check_privileges.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 cc46690a894d1..65a3d1bf1650b 100644 --- a/x-pack/plugins/security/server/authorization/check_privileges.test.ts +++ b/x-pack/plugins/security/server/authorization/check_privileges.test.ts @@ -737,7 +737,7 @@ describe('#atSpaces', () => { [`saved_object:${savedObjectTypes[0]}/get`]: false, [`saved_object:${savedObjectTypes[1]}/get`]: true, }, - // @ts-expect-error this is wrong on purpose + // @ts-ignore 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-expect-error this is wrong on purpose + // @ts-ignore this is wrong on purpose 'space:space_1': { [mockActions.login]: true, [mockActions.version]: true, From 1a68ea19d8b719760ec721003b64bfc7b1259a7a Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Fri, 3 Jul 2020 08:16:00 +0200 Subject: [PATCH 33/42] move response mocks to mocks.ts --- .../client/client_facade.mock.ts | 24 --------------- src/core/server/elasticsearch/client/mocks.ts | 30 +++++++++++++++++-- 2 files changed, 28 insertions(+), 26 deletions(-) diff --git a/src/core/server/elasticsearch/client/client_facade.mock.ts b/src/core/server/elasticsearch/client/client_facade.mock.ts index a9f6a74bfc0a3..f629d9fbbe04b 100644 --- a/src/core/server/elasticsearch/client/client_facade.mock.ts +++ b/src/core/server/elasticsearch/client/client_facade.mock.ts @@ -17,30 +17,8 @@ * under the License. */ -import { ApiResponse } from '@elastic/elasticsearch'; -import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport'; import { ClientFacade } from './client_facade'; -const createApiResponse = (body: T): TransportRequestPromise> => { - const response: ApiResponse = { - body, - statusCode: 200, - warnings: [], - headers: {}, - meta: {} as any, - }; - const promise = Promise.resolve(response); - (promise as TransportRequestPromise>).abort = () => undefined; - - return promise as TransportRequestPromise>; -}; - -const createApiError = (err: any): TransportRequestPromise => { - const promise = Promise.reject(err); - (promise as TransportRequestPromise).abort = () => undefined; - return promise as TransportRequestPromise; -}; - const createFacadeMock = () => { const mock: DeeplyMockedKeys = { transport: { @@ -435,6 +413,4 @@ const createFacadeMock = () => { export const clientFacadeMock = { create: createFacadeMock, - createApiResponse, - createApiError, }; diff --git a/src/core/server/elasticsearch/client/mocks.ts b/src/core/server/elasticsearch/client/mocks.ts index 58b60bf934847..377830351eff5 100644 --- a/src/core/server/elasticsearch/client/mocks.ts +++ b/src/core/server/elasticsearch/client/mocks.ts @@ -17,6 +17,8 @@ * under the License. */ +import { ApiResponse } from '@elastic/elasticsearch'; +import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport'; import { clientFacadeMock } from './client_facade.mock'; import { IScopedClusterClient } from './scoped_cluster_client'; import { IClusterClient, ICustomClusterClient } from './cluster_client'; @@ -58,11 +60,35 @@ const createCustomClusterClientMock = () => { return mock; }; +type MockedTransportRequestPromise = TransportRequestPromise & { + abort: jest.MockedFunction<() => undefined>; +}; + +const createMockedClientResponse = (body: T): MockedTransportRequestPromise> => { + const response: ApiResponse = { + body, + statusCode: 200, + warnings: [], + headers: {}, + meta: {} as any, + }; + const promise = Promise.resolve(response); + (promise as MockedTransportRequestPromise>).abort = jest.fn(); + + return promise as MockedTransportRequestPromise>; +}; + +const createMockedClientError = (err: any): MockedTransportRequestPromise => { + const promise = Promise.reject(err); + (promise as MockedTransportRequestPromise).abort = jest.fn(); + return promise as MockedTransportRequestPromise; +}; + export const elasticsearchClientMock = { createClusterClient: createClusterClientMock, createCustomClusterClient: createCustomClusterClientMock, createScopedClusterClient: createScopedClusterClientMock, createFacade: clientFacadeMock.create, - createClientResponse: clientFacadeMock.createApiResponse, - createClientError: clientFacadeMock.createApiError, + createClientResponse: createMockedClientResponse, + createClientError: createMockedClientError, }; From f956fb4450fdcb914d67d7976c67b5eb1fcfd500 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Fri, 3 Jul 2020 13:44:49 +0200 Subject: [PATCH 34/42] Remove generated facade, use ES Client directly --- .../client/client_facade.mock.ts | 416 ---- .../elasticsearch/client/client_facade.ts | 1858 ----------------- .../client/cluster_client.test.mocks.ts | 5 - .../client/cluster_client.test.ts | 167 +- .../elasticsearch/client/cluster_client.ts | 44 +- .../client/get_client_facade.test.ts | 87 - .../elasticsearch/client/get_client_facade.ts | 534 ----- src/core/server/elasticsearch/client/index.ts | 2 +- .../server/elasticsearch/client/mocks.test.ts | 60 + src/core/server/elasticsearch/client/mocks.ts | 59 +- .../client/scoped_cluster_client.test.ts | 8 +- .../client/scoped_cluster_client.ts | 14 +- .../core/server/elasticsearch/client/types.ts | 25 +- src/core/server/elasticsearch/index.ts | 2 +- src/core/server/server.api.md | 7 +- src/dev/generate_es_client.ts | 151 -- 16 files changed, 279 insertions(+), 3160 deletions(-) delete mode 100644 src/core/server/elasticsearch/client/client_facade.mock.ts delete mode 100644 src/core/server/elasticsearch/client/client_facade.ts delete mode 100644 src/core/server/elasticsearch/client/get_client_facade.test.ts delete mode 100644 src/core/server/elasticsearch/client/get_client_facade.ts create mode 100644 src/core/server/elasticsearch/client/mocks.test.ts rename scripts/generate_es_client.js => src/core/server/elasticsearch/client/types.ts (59%) delete mode 100644 src/dev/generate_es_client.ts diff --git a/src/core/server/elasticsearch/client/client_facade.mock.ts b/src/core/server/elasticsearch/client/client_facade.mock.ts deleted file mode 100644 index f629d9fbbe04b..0000000000000 --- a/src/core/server/elasticsearch/client/client_facade.mock.ts +++ /dev/null @@ -1,416 +0,0 @@ -/* - * 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 { ClientFacade } from './client_facade'; - -const createFacadeMock = () => { - const mock: DeeplyMockedKeys = { - transport: { - request: jest.fn(), - }, - /* GENERATED */ - asyncSearch: { - delete: jest.fn(), - get: jest.fn(), - submit: jest.fn(), - }, - autoscaling: { - deleteAutoscalingPolicy: jest.fn(), - getAutoscalingDecision: jest.fn(), - getAutoscalingPolicy: jest.fn(), - putAutoscalingPolicy: jest.fn(), - }, - bulk: jest.fn(), - cat: { - aliases: jest.fn(), - allocation: jest.fn(), - count: jest.fn(), - fielddata: jest.fn(), - health: jest.fn(), - help: jest.fn(), - indices: jest.fn(), - master: jest.fn(), - mlDataFrameAnalytics: jest.fn(), - mlDatafeeds: jest.fn(), - mlJobs: jest.fn(), - mlTrainedModels: jest.fn(), - nodeattrs: jest.fn(), - nodes: jest.fn(), - pendingTasks: jest.fn(), - plugins: jest.fn(), - recovery: jest.fn(), - repositories: jest.fn(), - segments: jest.fn(), - shards: jest.fn(), - snapshots: jest.fn(), - tasks: jest.fn(), - templates: jest.fn(), - threadPool: jest.fn(), - transforms: jest.fn(), - }, - ccr: { - deleteAutoFollowPattern: jest.fn(), - follow: jest.fn(), - followInfo: jest.fn(), - followStats: jest.fn(), - forgetFollower: jest.fn(), - getAutoFollowPattern: jest.fn(), - pauseAutoFollowPattern: jest.fn(), - pauseFollow: jest.fn(), - putAutoFollowPattern: jest.fn(), - resumeAutoFollowPattern: jest.fn(), - resumeFollow: jest.fn(), - stats: jest.fn(), - unfollow: jest.fn(), - }, - clearScroll: jest.fn(), - cluster: { - allocationExplain: jest.fn(), - deleteComponentTemplate: jest.fn(), - deleteVotingConfigExclusions: jest.fn(), - existsComponentTemplate: jest.fn(), - getComponentTemplate: jest.fn(), - getSettings: jest.fn(), - health: jest.fn(), - pendingTasks: jest.fn(), - postVotingConfigExclusions: jest.fn(), - putComponentTemplate: jest.fn(), - putSettings: jest.fn(), - remoteInfo: jest.fn(), - reroute: jest.fn(), - state: jest.fn(), - stats: jest.fn(), - }, - count: jest.fn(), - create: jest.fn(), - delete: jest.fn(), - deleteByQuery: jest.fn(), - deleteByQueryRethrottle: jest.fn(), - deleteScript: jest.fn(), - enrich: { - deletePolicy: jest.fn(), - executePolicy: jest.fn(), - getPolicy: jest.fn(), - putPolicy: jest.fn(), - stats: jest.fn(), - }, - eql: { - search: jest.fn(), - }, - exists: jest.fn(), - existsSource: jest.fn(), - explain: jest.fn(), - fieldCaps: jest.fn(), - get: jest.fn(), - getScript: jest.fn(), - getScriptContext: jest.fn(), - getScriptLanguages: jest.fn(), - getSource: jest.fn(), - graph: { - explore: jest.fn(), - }, - ilm: { - deleteLifecycle: jest.fn(), - explainLifecycle: jest.fn(), - getLifecycle: jest.fn(), - getStatus: jest.fn(), - moveToStep: jest.fn(), - putLifecycle: jest.fn(), - removePolicy: jest.fn(), - retry: jest.fn(), - start: jest.fn(), - stop: jest.fn(), - }, - index: jest.fn(), - indices: { - analyze: jest.fn(), - clearCache: jest.fn(), - clone: jest.fn(), - close: jest.fn(), - create: jest.fn(), - createDataStream: jest.fn(), - delete: jest.fn(), - deleteAlias: jest.fn(), - deleteDataStream: jest.fn(), - deleteIndexTemplate: jest.fn(), - deleteTemplate: jest.fn(), - exists: jest.fn(), - existsAlias: jest.fn(), - existsIndexTemplate: jest.fn(), - existsTemplate: jest.fn(), - existsType: jest.fn(), - flush: jest.fn(), - flushSynced: jest.fn(), - forcemerge: jest.fn(), - freeze: jest.fn(), - get: jest.fn(), - getAlias: jest.fn(), - getDataStreams: jest.fn(), - getFieldMapping: jest.fn(), - getIndexTemplate: jest.fn(), - getMapping: jest.fn(), - getSettings: jest.fn(), - getTemplate: jest.fn(), - getUpgrade: jest.fn(), - open: jest.fn(), - putAlias: jest.fn(), - putIndexTemplate: jest.fn(), - putMapping: jest.fn(), - putSettings: jest.fn(), - putTemplate: jest.fn(), - recovery: jest.fn(), - refresh: jest.fn(), - reloadSearchAnalyzers: jest.fn(), - rollover: jest.fn(), - segments: jest.fn(), - shardStores: jest.fn(), - shrink: jest.fn(), - simulateIndexTemplate: jest.fn(), - split: jest.fn(), - stats: jest.fn(), - unfreeze: jest.fn(), - updateAliases: jest.fn(), - upgrade: jest.fn(), - validateQuery: jest.fn(), - }, - info: jest.fn(), - ingest: { - deletePipeline: jest.fn(), - getPipeline: jest.fn(), - processorGrok: jest.fn(), - putPipeline: jest.fn(), - simulate: jest.fn(), - }, - license: { - delete: jest.fn(), - get: jest.fn(), - getBasicStatus: jest.fn(), - getTrialStatus: jest.fn(), - post: jest.fn(), - postStartBasic: jest.fn(), - postStartTrial: jest.fn(), - }, - mget: jest.fn(), - migration: { - deprecations: jest.fn(), - }, - ml: { - closeJob: jest.fn(), - deleteCalendar: jest.fn(), - deleteCalendarEvent: jest.fn(), - deleteCalendarJob: jest.fn(), - deleteDataFrameAnalytics: jest.fn(), - deleteDatafeed: jest.fn(), - deleteExpiredData: jest.fn(), - deleteFilter: jest.fn(), - deleteForecast: jest.fn(), - deleteJob: jest.fn(), - deleteModelSnapshot: jest.fn(), - deleteTrainedModel: jest.fn(), - estimateModelMemory: jest.fn(), - evaluateDataFrame: jest.fn(), - explainDataFrameAnalytics: jest.fn(), - findFileStructure: jest.fn(), - flushJob: jest.fn(), - forecast: jest.fn(), - getBuckets: jest.fn(), - getCalendarEvents: jest.fn(), - getCalendars: jest.fn(), - getCategories: jest.fn(), - getDataFrameAnalytics: jest.fn(), - getDataFrameAnalyticsStats: jest.fn(), - getDatafeedStats: jest.fn(), - getDatafeeds: jest.fn(), - getFilters: jest.fn(), - getInfluencers: jest.fn(), - getJobStats: jest.fn(), - getJobs: jest.fn(), - getModelSnapshots: jest.fn(), - getOverallBuckets: jest.fn(), - getRecords: jest.fn(), - getTrainedModels: jest.fn(), - getTrainedModelsStats: jest.fn(), - info: jest.fn(), - openJob: jest.fn(), - postCalendarEvents: jest.fn(), - postData: jest.fn(), - previewDatafeed: jest.fn(), - putCalendar: jest.fn(), - putCalendarJob: jest.fn(), - putDataFrameAnalytics: jest.fn(), - putDatafeed: jest.fn(), - putFilter: jest.fn(), - putJob: jest.fn(), - putTrainedModel: jest.fn(), - revertModelSnapshot: jest.fn(), - setUpgradeMode: jest.fn(), - startDataFrameAnalytics: jest.fn(), - startDatafeed: jest.fn(), - stopDataFrameAnalytics: jest.fn(), - stopDatafeed: jest.fn(), - updateDatafeed: jest.fn(), - updateFilter: jest.fn(), - updateJob: jest.fn(), - updateModelSnapshot: jest.fn(), - validate: jest.fn(), - validateDetector: jest.fn(), - }, - monitoring: { - bulk: jest.fn(), - }, - msearch: jest.fn(), - msearchTemplate: jest.fn(), - mtermvectors: jest.fn(), - nodes: { - hotThreads: jest.fn(), - info: jest.fn(), - reloadSecureSettings: jest.fn(), - stats: jest.fn(), - usage: jest.fn(), - }, - ping: jest.fn(), - putScript: jest.fn(), - rankEval: jest.fn(), - reindex: jest.fn(), - reindexRethrottle: jest.fn(), - renderSearchTemplate: jest.fn(), - rollup: { - deleteJob: jest.fn(), - getJobs: jest.fn(), - getRollupCaps: jest.fn(), - getRollupIndexCaps: jest.fn(), - putJob: jest.fn(), - rollupSearch: jest.fn(), - startJob: jest.fn(), - stopJob: jest.fn(), - }, - scriptsPainlessExecute: jest.fn(), - scroll: jest.fn(), - search: jest.fn(), - searchShards: jest.fn(), - searchTemplate: jest.fn(), - searchableSnapshots: { - clearCache: jest.fn(), - mount: jest.fn(), - repositoryStats: jest.fn(), - stats: jest.fn(), - }, - security: { - authenticate: jest.fn(), - changePassword: jest.fn(), - clearCachedRealms: jest.fn(), - clearCachedRoles: jest.fn(), - createApiKey: jest.fn(), - deletePrivileges: jest.fn(), - deleteRole: jest.fn(), - deleteRoleMapping: jest.fn(), - deleteUser: jest.fn(), - disableUser: jest.fn(), - enableUser: jest.fn(), - getApiKey: jest.fn(), - getBuiltinPrivileges: jest.fn(), - getPrivileges: jest.fn(), - getRole: jest.fn(), - getRoleMapping: jest.fn(), - getToken: jest.fn(), - getUser: jest.fn(), - getUserPrivileges: jest.fn(), - hasPrivileges: jest.fn(), - invalidateApiKey: jest.fn(), - invalidateToken: jest.fn(), - putPrivileges: jest.fn(), - putRole: jest.fn(), - putRoleMapping: jest.fn(), - putUser: jest.fn(), - }, - slm: { - deleteLifecycle: jest.fn(), - executeLifecycle: jest.fn(), - executeRetention: jest.fn(), - getLifecycle: jest.fn(), - getStats: jest.fn(), - getStatus: jest.fn(), - putLifecycle: jest.fn(), - start: jest.fn(), - stop: jest.fn(), - }, - snapshot: { - cleanupRepository: jest.fn(), - create: jest.fn(), - createRepository: jest.fn(), - delete: jest.fn(), - deleteRepository: jest.fn(), - get: jest.fn(), - getRepository: jest.fn(), - restore: jest.fn(), - status: jest.fn(), - verifyRepository: jest.fn(), - }, - sql: { - clearCursor: jest.fn(), - query: jest.fn(), - translate: jest.fn(), - }, - ssl: { - certificates: jest.fn(), - }, - tasks: { - cancel: jest.fn(), - get: jest.fn(), - list: jest.fn(), - }, - termvectors: jest.fn(), - transform: { - deleteTransform: jest.fn(), - getTransform: jest.fn(), - getTransformStats: jest.fn(), - previewTransform: jest.fn(), - putTransform: jest.fn(), - startTransform: jest.fn(), - stopTransform: jest.fn(), - updateTransform: jest.fn(), - }, - update: jest.fn(), - updateByQuery: jest.fn(), - updateByQueryRethrottle: jest.fn(), - watcher: { - ackWatch: jest.fn(), - activateWatch: jest.fn(), - deactivateWatch: jest.fn(), - deleteWatch: jest.fn(), - executeWatch: jest.fn(), - getWatch: jest.fn(), - putWatch: jest.fn(), - start: jest.fn(), - stats: jest.fn(), - stop: jest.fn(), - }, - xpack: { - info: jest.fn(), - usage: jest.fn(), - }, - /* /GENERATED */ - }; - - return mock; -}; - -export const clientFacadeMock = { - create: createFacadeMock, -}; diff --git a/src/core/server/elasticsearch/client/client_facade.ts b/src/core/server/elasticsearch/client/client_facade.ts deleted file mode 100644 index 0e7b12337853c..0000000000000 --- a/src/core/server/elasticsearch/client/client_facade.ts +++ /dev/null @@ -1,1858 +0,0 @@ -/* - * 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 { ApiResponse } from '@elastic/elasticsearch'; -import { - RequestBody, - RequestNDBody, - TransportRequestOptions, - TransportRequestParams, - TransportRequestPromise, -} from '@elastic/elasticsearch/lib/Transport'; -import * as RequestParams from '@elastic/elasticsearch/api/requestParams'; - -/** - * Facade used to query the elasticsearch cluster. - * - * @public - */ -export interface ClientFacade { - transport: { - request( - params: TransportRequestParams, - options?: TransportRequestOptions - ): Promise; - }; - /* GENERATED */ - asyncSearch: { - delete, TContext = unknown>( - params?: RequestParams.AsyncSearchDelete, - options?: TransportRequestOptions - ): TransportRequestPromise>; - get, TContext = unknown>( - params?: RequestParams.AsyncSearchGet, - options?: TransportRequestOptions - ): TransportRequestPromise>; - submit< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.AsyncSearchSubmit, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - autoscaling: { - deleteAutoscalingPolicy, TContext = unknown>( - params?: RequestParams.AutoscalingDeleteAutoscalingPolicy, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getAutoscalingDecision, TContext = unknown>( - params?: RequestParams.AutoscalingGetAutoscalingDecision, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getAutoscalingPolicy, TContext = unknown>( - params?: RequestParams.AutoscalingGetAutoscalingPolicy, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putAutoscalingPolicy< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.AutoscalingPutAutoscalingPolicy, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - bulk< - TResponse = Record, - TRequestBody extends RequestNDBody = Array>, - TContext = unknown - >( - params?: RequestParams.Bulk, - options?: TransportRequestOptions - ): TransportRequestPromise>; - cat: { - aliases, TContext = unknown>( - params?: RequestParams.CatAliases, - options?: TransportRequestOptions - ): TransportRequestPromise>; - allocation, TContext = unknown>( - params?: RequestParams.CatAllocation, - options?: TransportRequestOptions - ): TransportRequestPromise>; - count, TContext = unknown>( - params?: RequestParams.CatCount, - options?: TransportRequestOptions - ): TransportRequestPromise>; - fielddata, TContext = unknown>( - params?: RequestParams.CatFielddata, - options?: TransportRequestOptions - ): TransportRequestPromise>; - health, TContext = unknown>( - params?: RequestParams.CatHealth, - options?: TransportRequestOptions - ): TransportRequestPromise>; - help, TContext = unknown>( - params?: RequestParams.CatHelp, - options?: TransportRequestOptions - ): TransportRequestPromise>; - indices, TContext = unknown>( - params?: RequestParams.CatIndices, - options?: TransportRequestOptions - ): TransportRequestPromise>; - master, TContext = unknown>( - params?: RequestParams.CatMaster, - options?: TransportRequestOptions - ): TransportRequestPromise>; - mlDataFrameAnalytics, TContext = unknown>( - params?: RequestParams.CatMlDataFrameAnalytics, - options?: TransportRequestOptions - ): TransportRequestPromise>; - mlDatafeeds, TContext = unknown>( - params?: RequestParams.CatMlDatafeeds, - options?: TransportRequestOptions - ): TransportRequestPromise>; - mlJobs, TContext = unknown>( - params?: RequestParams.CatMlJobs, - options?: TransportRequestOptions - ): TransportRequestPromise>; - mlTrainedModels, TContext = unknown>( - params?: RequestParams.CatMlTrainedModels, - options?: TransportRequestOptions - ): TransportRequestPromise>; - nodeattrs, TContext = unknown>( - params?: RequestParams.CatNodeattrs, - options?: TransportRequestOptions - ): TransportRequestPromise>; - nodes, TContext = unknown>( - params?: RequestParams.CatNodes, - options?: TransportRequestOptions - ): TransportRequestPromise>; - pendingTasks, TContext = unknown>( - params?: RequestParams.CatPendingTasks, - options?: TransportRequestOptions - ): TransportRequestPromise>; - plugins, TContext = unknown>( - params?: RequestParams.CatPlugins, - options?: TransportRequestOptions - ): TransportRequestPromise>; - recovery, TContext = unknown>( - params?: RequestParams.CatRecovery, - options?: TransportRequestOptions - ): TransportRequestPromise>; - repositories, TContext = unknown>( - params?: RequestParams.CatRepositories, - options?: TransportRequestOptions - ): TransportRequestPromise>; - segments, TContext = unknown>( - params?: RequestParams.CatSegments, - options?: TransportRequestOptions - ): TransportRequestPromise>; - shards, TContext = unknown>( - params?: RequestParams.CatShards, - options?: TransportRequestOptions - ): TransportRequestPromise>; - snapshots, TContext = unknown>( - params?: RequestParams.CatSnapshots, - options?: TransportRequestOptions - ): TransportRequestPromise>; - tasks, TContext = unknown>( - params?: RequestParams.CatTasks, - options?: TransportRequestOptions - ): TransportRequestPromise>; - templates, TContext = unknown>( - params?: RequestParams.CatTemplates, - options?: TransportRequestOptions - ): TransportRequestPromise>; - threadPool, TContext = unknown>( - params?: RequestParams.CatThreadPool, - options?: TransportRequestOptions - ): TransportRequestPromise>; - transforms, TContext = unknown>( - params?: RequestParams.CatTransforms, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - ccr: { - deleteAutoFollowPattern, TContext = unknown>( - params?: RequestParams.CcrDeleteAutoFollowPattern, - options?: TransportRequestOptions - ): TransportRequestPromise>; - follow< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.CcrFollow, - options?: TransportRequestOptions - ): TransportRequestPromise>; - followInfo, TContext = unknown>( - params?: RequestParams.CcrFollowInfo, - options?: TransportRequestOptions - ): TransportRequestPromise>; - followStats, TContext = unknown>( - params?: RequestParams.CcrFollowStats, - options?: TransportRequestOptions - ): TransportRequestPromise>; - forgetFollower< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.CcrForgetFollower, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getAutoFollowPattern, TContext = unknown>( - params?: RequestParams.CcrGetAutoFollowPattern, - options?: TransportRequestOptions - ): TransportRequestPromise>; - pauseAutoFollowPattern, TContext = unknown>( - params?: RequestParams.CcrPauseAutoFollowPattern, - options?: TransportRequestOptions - ): TransportRequestPromise>; - pauseFollow, TContext = unknown>( - params?: RequestParams.CcrPauseFollow, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putAutoFollowPattern< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.CcrPutAutoFollowPattern, - options?: TransportRequestOptions - ): TransportRequestPromise>; - resumeAutoFollowPattern, TContext = unknown>( - params?: RequestParams.CcrResumeAutoFollowPattern, - options?: TransportRequestOptions - ): TransportRequestPromise>; - resumeFollow< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.CcrResumeFollow, - options?: TransportRequestOptions - ): TransportRequestPromise>; - stats, TContext = unknown>( - params?: RequestParams.CcrStats, - options?: TransportRequestOptions - ): TransportRequestPromise>; - unfollow, TContext = unknown>( - params?: RequestParams.CcrUnfollow, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - clearScroll< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.ClearScroll, - options?: TransportRequestOptions - ): TransportRequestPromise>; - cluster: { - allocationExplain< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.ClusterAllocationExplain, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteComponentTemplate, TContext = unknown>( - params?: RequestParams.ClusterDeleteComponentTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteVotingConfigExclusions, TContext = unknown>( - params?: RequestParams.ClusterDeleteVotingConfigExclusions, - options?: TransportRequestOptions - ): TransportRequestPromise>; - existsComponentTemplate, TContext = unknown>( - params?: RequestParams.ClusterExistsComponentTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getComponentTemplate, TContext = unknown>( - params?: RequestParams.ClusterGetComponentTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getSettings, TContext = unknown>( - params?: RequestParams.ClusterGetSettings, - options?: TransportRequestOptions - ): TransportRequestPromise>; - health, TContext = unknown>( - params?: RequestParams.ClusterHealth, - options?: TransportRequestOptions - ): TransportRequestPromise>; - pendingTasks, TContext = unknown>( - params?: RequestParams.ClusterPendingTasks, - options?: TransportRequestOptions - ): TransportRequestPromise>; - postVotingConfigExclusions, TContext = unknown>( - params?: RequestParams.ClusterPostVotingConfigExclusions, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putComponentTemplate< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.ClusterPutComponentTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putSettings< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.ClusterPutSettings, - options?: TransportRequestOptions - ): TransportRequestPromise>; - remoteInfo, TContext = unknown>( - params?: RequestParams.ClusterRemoteInfo, - options?: TransportRequestOptions - ): TransportRequestPromise>; - reroute< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.ClusterReroute, - options?: TransportRequestOptions - ): TransportRequestPromise>; - state, TContext = unknown>( - params?: RequestParams.ClusterState, - options?: TransportRequestOptions - ): TransportRequestPromise>; - stats, TContext = unknown>( - params?: RequestParams.ClusterStats, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - count< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.Count, - options?: TransportRequestOptions - ): TransportRequestPromise>; - create< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.Create, - options?: TransportRequestOptions - ): TransportRequestPromise>; - delete, TContext = unknown>( - params?: RequestParams.Delete, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteByQuery< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.DeleteByQuery, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteByQueryRethrottle, TContext = unknown>( - params?: RequestParams.DeleteByQueryRethrottle, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteScript, TContext = unknown>( - params?: RequestParams.DeleteScript, - options?: TransportRequestOptions - ): TransportRequestPromise>; - enrich: { - deletePolicy, TContext = unknown>( - params?: RequestParams.EnrichDeletePolicy, - options?: TransportRequestOptions - ): TransportRequestPromise>; - executePolicy, TContext = unknown>( - params?: RequestParams.EnrichExecutePolicy, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getPolicy, TContext = unknown>( - params?: RequestParams.EnrichGetPolicy, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putPolicy< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.EnrichPutPolicy, - options?: TransportRequestOptions - ): TransportRequestPromise>; - stats, TContext = unknown>( - params?: RequestParams.EnrichStats, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - eql: { - search< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.EqlSearch, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - exists, TContext = unknown>( - params?: RequestParams.Exists, - options?: TransportRequestOptions - ): TransportRequestPromise>; - existsSource, TContext = unknown>( - params?: RequestParams.ExistsSource, - options?: TransportRequestOptions - ): TransportRequestPromise>; - explain< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.Explain, - options?: TransportRequestOptions - ): TransportRequestPromise>; - fieldCaps, TContext = unknown>( - params?: RequestParams.FieldCaps, - options?: TransportRequestOptions - ): TransportRequestPromise>; - get, TContext = unknown>( - params?: RequestParams.Get, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getScript, TContext = unknown>( - params?: RequestParams.GetScript, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getScriptContext, TContext = unknown>( - params?: RequestParams.GetScriptContext, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getScriptLanguages, TContext = unknown>( - params?: RequestParams.GetScriptLanguages, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getSource, TContext = unknown>( - params?: RequestParams.GetSource, - options?: TransportRequestOptions - ): TransportRequestPromise>; - graph: { - explore< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.GraphExplore, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - ilm: { - deleteLifecycle, TContext = unknown>( - params?: RequestParams.IlmDeleteLifecycle, - options?: TransportRequestOptions - ): TransportRequestPromise>; - explainLifecycle, TContext = unknown>( - params?: RequestParams.IlmExplainLifecycle, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getLifecycle, TContext = unknown>( - params?: RequestParams.IlmGetLifecycle, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getStatus, TContext = unknown>( - params?: RequestParams.IlmGetStatus, - options?: TransportRequestOptions - ): TransportRequestPromise>; - moveToStep< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IlmMoveToStep, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putLifecycle< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IlmPutLifecycle, - options?: TransportRequestOptions - ): TransportRequestPromise>; - removePolicy, TContext = unknown>( - params?: RequestParams.IlmRemovePolicy, - options?: TransportRequestOptions - ): TransportRequestPromise>; - retry, TContext = unknown>( - params?: RequestParams.IlmRetry, - options?: TransportRequestOptions - ): TransportRequestPromise>; - start, TContext = unknown>( - params?: RequestParams.IlmStart, - options?: TransportRequestOptions - ): TransportRequestPromise>; - stop, TContext = unknown>( - params?: RequestParams.IlmStop, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - index< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.Index, - options?: TransportRequestOptions - ): TransportRequestPromise>; - indices: { - analyze< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IndicesAnalyze, - options?: TransportRequestOptions - ): TransportRequestPromise>; - clearCache, TContext = unknown>( - params?: RequestParams.IndicesClearCache, - options?: TransportRequestOptions - ): TransportRequestPromise>; - clone< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IndicesClone, - options?: TransportRequestOptions - ): TransportRequestPromise>; - close, TContext = unknown>( - params?: RequestParams.IndicesClose, - options?: TransportRequestOptions - ): TransportRequestPromise>; - create< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IndicesCreate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - createDataStream< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IndicesCreateDataStream, - options?: TransportRequestOptions - ): TransportRequestPromise>; - delete, TContext = unknown>( - params?: RequestParams.IndicesDelete, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteAlias, TContext = unknown>( - params?: RequestParams.IndicesDeleteAlias, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteDataStream, TContext = unknown>( - params?: RequestParams.IndicesDeleteDataStream, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteIndexTemplate, TContext = unknown>( - params?: RequestParams.IndicesDeleteIndexTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteTemplate, TContext = unknown>( - params?: RequestParams.IndicesDeleteTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - exists, TContext = unknown>( - params?: RequestParams.IndicesExists, - options?: TransportRequestOptions - ): TransportRequestPromise>; - existsAlias, TContext = unknown>( - params?: RequestParams.IndicesExistsAlias, - options?: TransportRequestOptions - ): TransportRequestPromise>; - existsIndexTemplate, TContext = unknown>( - params?: RequestParams.IndicesExistsIndexTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - existsTemplate, TContext = unknown>( - params?: RequestParams.IndicesExistsTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - existsType, TContext = unknown>( - params?: RequestParams.IndicesExistsType, - options?: TransportRequestOptions - ): TransportRequestPromise>; - flush, TContext = unknown>( - params?: RequestParams.IndicesFlush, - options?: TransportRequestOptions - ): TransportRequestPromise>; - flushSynced, TContext = unknown>( - params?: RequestParams.IndicesFlushSynced, - options?: TransportRequestOptions - ): TransportRequestPromise>; - forcemerge, TContext = unknown>( - params?: RequestParams.IndicesForcemerge, - options?: TransportRequestOptions - ): TransportRequestPromise>; - freeze, TContext = unknown>( - params?: RequestParams.IndicesFreeze, - options?: TransportRequestOptions - ): TransportRequestPromise>; - get, TContext = unknown>( - params?: RequestParams.IndicesGet, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getAlias, TContext = unknown>( - params?: RequestParams.IndicesGetAlias, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getDataStreams, TContext = unknown>( - params?: RequestParams.IndicesGetDataStreams, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getFieldMapping, TContext = unknown>( - params?: RequestParams.IndicesGetFieldMapping, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getIndexTemplate, TContext = unknown>( - params?: RequestParams.IndicesGetIndexTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getMapping, TContext = unknown>( - params?: RequestParams.IndicesGetMapping, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getSettings, TContext = unknown>( - params?: RequestParams.IndicesGetSettings, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getTemplate, TContext = unknown>( - params?: RequestParams.IndicesGetTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getUpgrade, TContext = unknown>( - params?: RequestParams.IndicesGetUpgrade, - options?: TransportRequestOptions - ): TransportRequestPromise>; - open, TContext = unknown>( - params?: RequestParams.IndicesOpen, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putAlias< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IndicesPutAlias, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putIndexTemplate< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IndicesPutIndexTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putMapping< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IndicesPutMapping, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putSettings< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IndicesPutSettings, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putTemplate< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IndicesPutTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - recovery, TContext = unknown>( - params?: RequestParams.IndicesRecovery, - options?: TransportRequestOptions - ): TransportRequestPromise>; - refresh, TContext = unknown>( - params?: RequestParams.IndicesRefresh, - options?: TransportRequestOptions - ): TransportRequestPromise>; - reloadSearchAnalyzers, TContext = unknown>( - params?: RequestParams.IndicesReloadSearchAnalyzers, - options?: TransportRequestOptions - ): TransportRequestPromise>; - rollover< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IndicesRollover, - options?: TransportRequestOptions - ): TransportRequestPromise>; - segments, TContext = unknown>( - params?: RequestParams.IndicesSegments, - options?: TransportRequestOptions - ): TransportRequestPromise>; - shardStores, TContext = unknown>( - params?: RequestParams.IndicesShardStores, - options?: TransportRequestOptions - ): TransportRequestPromise>; - shrink< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IndicesShrink, - options?: TransportRequestOptions - ): TransportRequestPromise>; - simulateIndexTemplate< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IndicesSimulateIndexTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - split< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IndicesSplit, - options?: TransportRequestOptions - ): TransportRequestPromise>; - stats, TContext = unknown>( - params?: RequestParams.IndicesStats, - options?: TransportRequestOptions - ): TransportRequestPromise>; - unfreeze, TContext = unknown>( - params?: RequestParams.IndicesUnfreeze, - options?: TransportRequestOptions - ): TransportRequestPromise>; - updateAliases< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IndicesUpdateAliases, - options?: TransportRequestOptions - ): TransportRequestPromise>; - upgrade, TContext = unknown>( - params?: RequestParams.IndicesUpgrade, - options?: TransportRequestOptions - ): TransportRequestPromise>; - validateQuery< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IndicesValidateQuery, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - info, TContext = unknown>( - params?: RequestParams.Info, - options?: TransportRequestOptions - ): TransportRequestPromise>; - ingest: { - deletePipeline, TContext = unknown>( - params?: RequestParams.IngestDeletePipeline, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getPipeline, TContext = unknown>( - params?: RequestParams.IngestGetPipeline, - options?: TransportRequestOptions - ): TransportRequestPromise>; - processorGrok, TContext = unknown>( - params?: RequestParams.IngestProcessorGrok, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putPipeline< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IngestPutPipeline, - options?: TransportRequestOptions - ): TransportRequestPromise>; - simulate< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.IngestSimulate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - license: { - delete, TContext = unknown>( - params?: RequestParams.LicenseDelete, - options?: TransportRequestOptions - ): TransportRequestPromise>; - get, TContext = unknown>( - params?: RequestParams.LicenseGet, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getBasicStatus, TContext = unknown>( - params?: RequestParams.LicenseGetBasicStatus, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getTrialStatus, TContext = unknown>( - params?: RequestParams.LicenseGetTrialStatus, - options?: TransportRequestOptions - ): TransportRequestPromise>; - post< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.LicensePost, - options?: TransportRequestOptions - ): TransportRequestPromise>; - postStartBasic, TContext = unknown>( - params?: RequestParams.LicensePostStartBasic, - options?: TransportRequestOptions - ): TransportRequestPromise>; - postStartTrial, TContext = unknown>( - params?: RequestParams.LicensePostStartTrial, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - mget< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.Mget, - options?: TransportRequestOptions - ): TransportRequestPromise>; - migration: { - deprecations, TContext = unknown>( - params?: RequestParams.MigrationDeprecations, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - ml: { - closeJob< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlCloseJob, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteCalendar, TContext = unknown>( - params?: RequestParams.MlDeleteCalendar, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteCalendarEvent, TContext = unknown>( - params?: RequestParams.MlDeleteCalendarEvent, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteCalendarJob, TContext = unknown>( - params?: RequestParams.MlDeleteCalendarJob, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteDataFrameAnalytics, TContext = unknown>( - params?: RequestParams.MlDeleteDataFrameAnalytics, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteDatafeed, TContext = unknown>( - params?: RequestParams.MlDeleteDatafeed, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteExpiredData< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlDeleteExpiredData, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteFilter, TContext = unknown>( - params?: RequestParams.MlDeleteFilter, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteForecast, TContext = unknown>( - params?: RequestParams.MlDeleteForecast, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteJob, TContext = unknown>( - params?: RequestParams.MlDeleteJob, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteModelSnapshot, TContext = unknown>( - params?: RequestParams.MlDeleteModelSnapshot, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteTrainedModel, TContext = unknown>( - params?: RequestParams.MlDeleteTrainedModel, - options?: TransportRequestOptions - ): TransportRequestPromise>; - estimateModelMemory< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlEstimateModelMemory, - options?: TransportRequestOptions - ): TransportRequestPromise>; - evaluateDataFrame< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlEvaluateDataFrame, - options?: TransportRequestOptions - ): TransportRequestPromise>; - explainDataFrameAnalytics< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlExplainDataFrameAnalytics, - options?: TransportRequestOptions - ): TransportRequestPromise>; - findFileStructure< - TResponse = Record, - TRequestBody extends RequestNDBody = Array>, - TContext = unknown - >( - params?: RequestParams.MlFindFileStructure, - options?: TransportRequestOptions - ): TransportRequestPromise>; - flushJob< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlFlushJob, - options?: TransportRequestOptions - ): TransportRequestPromise>; - forecast, TContext = unknown>( - params?: RequestParams.MlForecast, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getBuckets< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlGetBuckets, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getCalendarEvents, TContext = unknown>( - params?: RequestParams.MlGetCalendarEvents, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getCalendars< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlGetCalendars, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getCategories< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlGetCategories, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getDataFrameAnalytics, TContext = unknown>( - params?: RequestParams.MlGetDataFrameAnalytics, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getDataFrameAnalyticsStats, TContext = unknown>( - params?: RequestParams.MlGetDataFrameAnalyticsStats, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getDatafeedStats, TContext = unknown>( - params?: RequestParams.MlGetDatafeedStats, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getDatafeeds, TContext = unknown>( - params?: RequestParams.MlGetDatafeeds, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getFilters, TContext = unknown>( - params?: RequestParams.MlGetFilters, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getInfluencers< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlGetInfluencers, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getJobStats, TContext = unknown>( - params?: RequestParams.MlGetJobStats, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getJobs, TContext = unknown>( - params?: RequestParams.MlGetJobs, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getModelSnapshots< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlGetModelSnapshots, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getOverallBuckets< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlGetOverallBuckets, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getRecords< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlGetRecords, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getTrainedModels, TContext = unknown>( - params?: RequestParams.MlGetTrainedModels, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getTrainedModelsStats, TContext = unknown>( - params?: RequestParams.MlGetTrainedModelsStats, - options?: TransportRequestOptions - ): TransportRequestPromise>; - info, TContext = unknown>( - params?: RequestParams.MlInfo, - options?: TransportRequestOptions - ): TransportRequestPromise>; - openJob, TContext = unknown>( - params?: RequestParams.MlOpenJob, - options?: TransportRequestOptions - ): TransportRequestPromise>; - postCalendarEvents< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlPostCalendarEvents, - options?: TransportRequestOptions - ): TransportRequestPromise>; - postData< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlPostData, - options?: TransportRequestOptions - ): TransportRequestPromise>; - previewDatafeed, TContext = unknown>( - params?: RequestParams.MlPreviewDatafeed, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putCalendar< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlPutCalendar, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putCalendarJob, TContext = unknown>( - params?: RequestParams.MlPutCalendarJob, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putDataFrameAnalytics< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlPutDataFrameAnalytics, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putDatafeed< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlPutDatafeed, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putFilter< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlPutFilter, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putJob< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlPutJob, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putTrainedModel< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlPutTrainedModel, - options?: TransportRequestOptions - ): TransportRequestPromise>; - revertModelSnapshot< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlRevertModelSnapshot, - options?: TransportRequestOptions - ): TransportRequestPromise>; - setUpgradeMode, TContext = unknown>( - params?: RequestParams.MlSetUpgradeMode, - options?: TransportRequestOptions - ): TransportRequestPromise>; - startDataFrameAnalytics< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlStartDataFrameAnalytics, - options?: TransportRequestOptions - ): TransportRequestPromise>; - startDatafeed< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlStartDatafeed, - options?: TransportRequestOptions - ): TransportRequestPromise>; - stopDataFrameAnalytics< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlStopDataFrameAnalytics, - options?: TransportRequestOptions - ): TransportRequestPromise>; - stopDatafeed, TContext = unknown>( - params?: RequestParams.MlStopDatafeed, - options?: TransportRequestOptions - ): TransportRequestPromise>; - updateDatafeed< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlUpdateDatafeed, - options?: TransportRequestOptions - ): TransportRequestPromise>; - updateFilter< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlUpdateFilter, - options?: TransportRequestOptions - ): TransportRequestPromise>; - updateJob< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlUpdateJob, - options?: TransportRequestOptions - ): TransportRequestPromise>; - updateModelSnapshot< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlUpdateModelSnapshot, - options?: TransportRequestOptions - ): TransportRequestPromise>; - validate< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlValidate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - validateDetector< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.MlValidateDetector, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - monitoring: { - bulk< - TResponse = Record, - TRequestBody extends RequestNDBody = Array>, - TContext = unknown - >( - params?: RequestParams.MonitoringBulk, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - msearch< - TResponse = Record, - TRequestBody extends RequestNDBody = Array>, - TContext = unknown - >( - params?: RequestParams.Msearch, - options?: TransportRequestOptions - ): TransportRequestPromise>; - msearchTemplate< - TResponse = Record, - TRequestBody extends RequestNDBody = Array>, - TContext = unknown - >( - params?: RequestParams.MsearchTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - mtermvectors< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.Mtermvectors, - options?: TransportRequestOptions - ): TransportRequestPromise>; - nodes: { - hotThreads, TContext = unknown>( - params?: RequestParams.NodesHotThreads, - options?: TransportRequestOptions - ): TransportRequestPromise>; - info, TContext = unknown>( - params?: RequestParams.NodesInfo, - options?: TransportRequestOptions - ): TransportRequestPromise>; - reloadSecureSettings< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.NodesReloadSecureSettings, - options?: TransportRequestOptions - ): TransportRequestPromise>; - stats, TContext = unknown>( - params?: RequestParams.NodesStats, - options?: TransportRequestOptions - ): TransportRequestPromise>; - usage, TContext = unknown>( - params?: RequestParams.NodesUsage, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - ping, TContext = unknown>( - params?: RequestParams.Ping, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putScript< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.PutScript, - options?: TransportRequestOptions - ): TransportRequestPromise>; - rankEval< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.RankEval, - options?: TransportRequestOptions - ): TransportRequestPromise>; - reindex< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.Reindex, - options?: TransportRequestOptions - ): TransportRequestPromise>; - reindexRethrottle, TContext = unknown>( - params?: RequestParams.ReindexRethrottle, - options?: TransportRequestOptions - ): TransportRequestPromise>; - renderSearchTemplate< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.RenderSearchTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - rollup: { - deleteJob, TContext = unknown>( - params?: RequestParams.RollupDeleteJob, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getJobs, TContext = unknown>( - params?: RequestParams.RollupGetJobs, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getRollupCaps, TContext = unknown>( - params?: RequestParams.RollupGetRollupCaps, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getRollupIndexCaps, TContext = unknown>( - params?: RequestParams.RollupGetRollupIndexCaps, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putJob< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.RollupPutJob, - options?: TransportRequestOptions - ): TransportRequestPromise>; - rollupSearch< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.RollupRollupSearch, - options?: TransportRequestOptions - ): TransportRequestPromise>; - startJob, TContext = unknown>( - params?: RequestParams.RollupStartJob, - options?: TransportRequestOptions - ): TransportRequestPromise>; - stopJob, TContext = unknown>( - params?: RequestParams.RollupStopJob, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - scriptsPainlessExecute< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.ScriptsPainlessExecute, - options?: TransportRequestOptions - ): TransportRequestPromise>; - scroll< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.Scroll, - options?: TransportRequestOptions - ): TransportRequestPromise>; - search< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.Search, - options?: TransportRequestOptions - ): TransportRequestPromise>; - searchShards, TContext = unknown>( - params?: RequestParams.SearchShards, - options?: TransportRequestOptions - ): TransportRequestPromise>; - searchTemplate< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SearchTemplate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - searchableSnapshots: { - clearCache, TContext = unknown>( - params?: RequestParams.SearchableSnapshotsClearCache, - options?: TransportRequestOptions - ): TransportRequestPromise>; - mount< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SearchableSnapshotsMount, - options?: TransportRequestOptions - ): TransportRequestPromise>; - repositoryStats, TContext = unknown>( - params?: RequestParams.SearchableSnapshotsRepositoryStats, - options?: TransportRequestOptions - ): TransportRequestPromise>; - stats, TContext = unknown>( - params?: RequestParams.SearchableSnapshotsStats, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - security: { - authenticate, TContext = unknown>( - params?: RequestParams.SecurityAuthenticate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - changePassword< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SecurityChangePassword, - options?: TransportRequestOptions - ): TransportRequestPromise>; - clearCachedRealms, TContext = unknown>( - params?: RequestParams.SecurityClearCachedRealms, - options?: TransportRequestOptions - ): TransportRequestPromise>; - clearCachedRoles, TContext = unknown>( - params?: RequestParams.SecurityClearCachedRoles, - options?: TransportRequestOptions - ): TransportRequestPromise>; - createApiKey< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SecurityCreateApiKey, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deletePrivileges, TContext = unknown>( - params?: RequestParams.SecurityDeletePrivileges, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteRole, TContext = unknown>( - params?: RequestParams.SecurityDeleteRole, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteRoleMapping, TContext = unknown>( - params?: RequestParams.SecurityDeleteRoleMapping, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteUser, TContext = unknown>( - params?: RequestParams.SecurityDeleteUser, - options?: TransportRequestOptions - ): TransportRequestPromise>; - disableUser, TContext = unknown>( - params?: RequestParams.SecurityDisableUser, - options?: TransportRequestOptions - ): TransportRequestPromise>; - enableUser, TContext = unknown>( - params?: RequestParams.SecurityEnableUser, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getApiKey, TContext = unknown>( - params?: RequestParams.SecurityGetApiKey, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getBuiltinPrivileges, TContext = unknown>( - params?: RequestParams.SecurityGetBuiltinPrivileges, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getPrivileges, TContext = unknown>( - params?: RequestParams.SecurityGetPrivileges, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getRole, TContext = unknown>( - params?: RequestParams.SecurityGetRole, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getRoleMapping, TContext = unknown>( - params?: RequestParams.SecurityGetRoleMapping, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getToken< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SecurityGetToken, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getUser, TContext = unknown>( - params?: RequestParams.SecurityGetUser, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getUserPrivileges, TContext = unknown>( - params?: RequestParams.SecurityGetUserPrivileges, - options?: TransportRequestOptions - ): TransportRequestPromise>; - hasPrivileges< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SecurityHasPrivileges, - options?: TransportRequestOptions - ): TransportRequestPromise>; - invalidateApiKey< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SecurityInvalidateApiKey, - options?: TransportRequestOptions - ): TransportRequestPromise>; - invalidateToken< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SecurityInvalidateToken, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putPrivileges< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SecurityPutPrivileges, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putRole< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SecurityPutRole, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putRoleMapping< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SecurityPutRoleMapping, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putUser< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SecurityPutUser, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - slm: { - deleteLifecycle, TContext = unknown>( - params?: RequestParams.SlmDeleteLifecycle, - options?: TransportRequestOptions - ): TransportRequestPromise>; - executeLifecycle, TContext = unknown>( - params?: RequestParams.SlmExecuteLifecycle, - options?: TransportRequestOptions - ): TransportRequestPromise>; - executeRetention, TContext = unknown>( - params?: RequestParams.SlmExecuteRetention, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getLifecycle, TContext = unknown>( - params?: RequestParams.SlmGetLifecycle, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getStats, TContext = unknown>( - params?: RequestParams.SlmGetStats, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getStatus, TContext = unknown>( - params?: RequestParams.SlmGetStatus, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putLifecycle< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SlmPutLifecycle, - options?: TransportRequestOptions - ): TransportRequestPromise>; - start, TContext = unknown>( - params?: RequestParams.SlmStart, - options?: TransportRequestOptions - ): TransportRequestPromise>; - stop, TContext = unknown>( - params?: RequestParams.SlmStop, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - snapshot: { - cleanupRepository, TContext = unknown>( - params?: RequestParams.SnapshotCleanupRepository, - options?: TransportRequestOptions - ): TransportRequestPromise>; - create< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SnapshotCreate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - createRepository< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SnapshotCreateRepository, - options?: TransportRequestOptions - ): TransportRequestPromise>; - delete, TContext = unknown>( - params?: RequestParams.SnapshotDelete, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteRepository, TContext = unknown>( - params?: RequestParams.SnapshotDeleteRepository, - options?: TransportRequestOptions - ): TransportRequestPromise>; - get, TContext = unknown>( - params?: RequestParams.SnapshotGet, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getRepository, TContext = unknown>( - params?: RequestParams.SnapshotGetRepository, - options?: TransportRequestOptions - ): TransportRequestPromise>; - restore< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SnapshotRestore, - options?: TransportRequestOptions - ): TransportRequestPromise>; - status, TContext = unknown>( - params?: RequestParams.SnapshotStatus, - options?: TransportRequestOptions - ): TransportRequestPromise>; - verifyRepository, TContext = unknown>( - params?: RequestParams.SnapshotVerifyRepository, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - sql: { - clearCursor< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SqlClearCursor, - options?: TransportRequestOptions - ): TransportRequestPromise>; - query< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SqlQuery, - options?: TransportRequestOptions - ): TransportRequestPromise>; - translate< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.SqlTranslate, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - ssl: { - certificates, TContext = unknown>( - params?: RequestParams.SslCertificates, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - tasks: { - cancel, TContext = unknown>( - params?: RequestParams.TasksCancel, - options?: TransportRequestOptions - ): TransportRequestPromise>; - get, TContext = unknown>( - params?: RequestParams.TasksGet, - options?: TransportRequestOptions - ): TransportRequestPromise>; - list, TContext = unknown>( - params?: RequestParams.TasksList, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - termvectors< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.Termvectors, - options?: TransportRequestOptions - ): TransportRequestPromise>; - transform: { - deleteTransform, TContext = unknown>( - params?: RequestParams.TransformDeleteTransform, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getTransform, TContext = unknown>( - params?: RequestParams.TransformGetTransform, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getTransformStats, TContext = unknown>( - params?: RequestParams.TransformGetTransformStats, - options?: TransportRequestOptions - ): TransportRequestPromise>; - previewTransform< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.TransformPreviewTransform, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putTransform< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.TransformPutTransform, - options?: TransportRequestOptions - ): TransportRequestPromise>; - startTransform, TContext = unknown>( - params?: RequestParams.TransformStartTransform, - options?: TransportRequestOptions - ): TransportRequestPromise>; - stopTransform, TContext = unknown>( - params?: RequestParams.TransformStopTransform, - options?: TransportRequestOptions - ): TransportRequestPromise>; - updateTransform< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.TransformUpdateTransform, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - update< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.Update, - options?: TransportRequestOptions - ): TransportRequestPromise>; - updateByQuery< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.UpdateByQuery, - options?: TransportRequestOptions - ): TransportRequestPromise>; - updateByQueryRethrottle, TContext = unknown>( - params?: RequestParams.UpdateByQueryRethrottle, - options?: TransportRequestOptions - ): TransportRequestPromise>; - watcher: { - ackWatch, TContext = unknown>( - params?: RequestParams.WatcherAckWatch, - options?: TransportRequestOptions - ): TransportRequestPromise>; - activateWatch, TContext = unknown>( - params?: RequestParams.WatcherActivateWatch, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deactivateWatch, TContext = unknown>( - params?: RequestParams.WatcherDeactivateWatch, - options?: TransportRequestOptions - ): TransportRequestPromise>; - deleteWatch, TContext = unknown>( - params?: RequestParams.WatcherDeleteWatch, - options?: TransportRequestOptions - ): TransportRequestPromise>; - executeWatch< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.WatcherExecuteWatch, - options?: TransportRequestOptions - ): TransportRequestPromise>; - getWatch, TContext = unknown>( - params?: RequestParams.WatcherGetWatch, - options?: TransportRequestOptions - ): TransportRequestPromise>; - putWatch< - TResponse = Record, - TRequestBody extends RequestBody = Record, - TContext = unknown - >( - params?: RequestParams.WatcherPutWatch, - options?: TransportRequestOptions - ): TransportRequestPromise>; - start, TContext = unknown>( - params?: RequestParams.WatcherStart, - options?: TransportRequestOptions - ): TransportRequestPromise>; - stats, TContext = unknown>( - params?: RequestParams.WatcherStats, - options?: TransportRequestOptions - ): TransportRequestPromise>; - stop, TContext = unknown>( - params?: RequestParams.WatcherStop, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - xpack: { - info, TContext = unknown>( - params?: RequestParams.XpackInfo, - options?: TransportRequestOptions - ): TransportRequestPromise>; - usage, TContext = unknown>( - params?: RequestParams.XpackUsage, - options?: TransportRequestOptions - ): TransportRequestPromise>; - }; - /* /GENERATED */ -} diff --git a/src/core/server/elasticsearch/client/cluster_client.test.mocks.ts b/src/core/server/elasticsearch/client/cluster_client.test.mocks.ts index 35d0093c16189..e08c0d55b4551 100644 --- a/src/core/server/elasticsearch/client/cluster_client.test.mocks.ts +++ b/src/core/server/elasticsearch/client/cluster_client.test.mocks.ts @@ -21,8 +21,3 @@ export const configureClientMock = jest.fn(); jest.doMock('./configure_client', () => ({ configureClient: configureClientMock, })); - -export const getClientFacadeMock = jest.fn(); -jest.doMock('./get_client_facade', () => ({ - getClientFacade: getClientFacadeMock, -})); diff --git a/src/core/server/elasticsearch/client/cluster_client.test.ts b/src/core/server/elasticsearch/client/cluster_client.test.ts index e02d16b3049a4..0d2274b67e8fe 100644 --- a/src/core/server/elasticsearch/client/cluster_client.test.ts +++ b/src/core/server/elasticsearch/client/cluster_client.test.ts @@ -17,8 +17,7 @@ * under the License. */ -import type { Client } from '@elastic/elasticsearch'; -import { configureClientMock, getClientFacadeMock } from './cluster_client.test.mocks'; +import { configureClientMock } from './cluster_client.test.mocks'; import { loggingSystemMock } from '../../logging/logging_system.mock'; import { httpServerMock } from '../../http/http_server.mocks'; import { GetAuthHeaders } from '../../http'; @@ -26,12 +25,6 @@ import { elasticsearchClientMock } from './mocks'; import { ClusterClient } from './cluster_client'; import { ElasticsearchClientConfig } from './client_config'; -const createClientMock = (): jest.Mocked => { - return ({ - close: jest.fn(), - } as unknown) as jest.Mocked; -}; - const createConfig = ( parts: Partial = {} ): ElasticsearchClientConfig => { @@ -50,15 +43,13 @@ const createConfig = ( describe('ClusterClient', () => { let logger: ReturnType; let getAuthHeaders: jest.MockedFunction; - let internalClient: jest.Mocked; - let scopedClient: jest.Mocked; - let internalFacade: ReturnType; + let internalClient: ReturnType; + let scopedClient: ReturnType; beforeEach(() => { logger = loggingSystemMock.createLogger(); - internalClient = createClientMock(); - scopedClient = createClientMock(); - internalFacade = elasticsearchClientMock.createFacade(); + internalClient = elasticsearchClientMock.createInternalClient(); + scopedClient = elasticsearchClientMock.createInternalClient(); getAuthHeaders = jest.fn().mockImplementation(() => ({ authorization: 'auth', foo: 'bar', @@ -67,18 +58,10 @@ describe('ClusterClient', () => { configureClientMock.mockImplementation((config, { scoped = false }) => { return scoped ? scopedClient : internalClient; }); - - getClientFacadeMock.mockImplementation((client) => { - if (client === internalClient) { - return internalFacade; - } - return elasticsearchClientMock.createFacade(); - }); }); afterEach(() => { configureClientMock.mockReset(); - getClientFacadeMock.mockReset(); }); it('creates a single internal and scoped client during initialization', () => { @@ -89,19 +72,13 @@ describe('ClusterClient', () => { expect(configureClientMock).toHaveBeenCalledTimes(2); expect(configureClientMock).toHaveBeenCalledWith(config, { logger }); expect(configureClientMock).toHaveBeenCalledWith(config, { logger, scoped: true }); - - expect(getClientFacadeMock).toHaveBeenCalledTimes(1); - expect(getClientFacadeMock).toHaveBeenCalledWith(internalClient); }); describe('#asInternalUser', () => { - it('returns the facade using the internal client', () => { + it('returns the internal client', () => { const clusterClient = new ClusterClient(createConfig(), logger, getAuthHeaders); - getClientFacadeMock.mockClear(); - - expect(clusterClient.asInternalUser()).toBe(internalFacade); - expect(getClientFacadeMock).not.toHaveBeenCalled(); + expect(clusterClient.asInternalUser()).toBe(internalClient); }); }); @@ -110,33 +87,29 @@ describe('ClusterClient', () => { const clusterClient = new ClusterClient(createConfig(), logger, getAuthHeaders); const request = httpServerMock.createKibanaRequest(); - getClientFacadeMock.mockClear(); - const scopedClusterClient = clusterClient.asScoped(request); - expect(getClientFacadeMock).toHaveBeenCalledTimes(1); - expect(getClientFacadeMock).toHaveBeenCalledWith(scopedClient, expect.any(Object)); + expect(scopedClient.child).toHaveBeenCalledTimes(1); + expect(scopedClient.child).toHaveBeenCalledWith({ headers: expect.any(Object) }); expect(scopedClusterClient.asInternalUser()).toBe(clusterClient.asInternalUser()); - expect(scopedClusterClient.asCurrentUser()).toBe(getClientFacadeMock.mock.results[0].value); + expect(scopedClusterClient.asCurrentUser()).toBe(scopedClient.child.mock.results[0].value); }); - it('returns a distinct facade on each call', () => { + it('returns a distinct scoped cluster client on each call', () => { const clusterClient = new ClusterClient(createConfig(), logger, getAuthHeaders); const request = httpServerMock.createKibanaRequest(); - getClientFacadeMock.mockClear(); - const scopedClusterClient1 = clusterClient.asScoped(request); const scopedClusterClient2 = clusterClient.asScoped(request); - expect(getClientFacadeMock).toHaveBeenCalledTimes(2); + expect(scopedClient.child).toHaveBeenCalledTimes(2); expect(scopedClusterClient1).not.toBe(scopedClusterClient2); expect(scopedClusterClient1.asInternalUser()).toBe(scopedClusterClient2.asInternalUser()); }); - it('creates a scoped facade with filtered request headers', () => { + it('creates a scoped client with filtered request headers', () => { const config = createConfig({ requestHeadersWhitelist: ['foo'], }); @@ -150,13 +123,11 @@ describe('ClusterClient', () => { }, }); - getClientFacadeMock.mockClear(); - clusterClient.asScoped(request); - expect(getClientFacadeMock).toHaveBeenCalledTimes(1); - expect(getClientFacadeMock).toHaveBeenCalledWith(scopedClient, { - foo: 'bar', + expect(scopedClient.child).toHaveBeenCalledTimes(1); + expect(scopedClient.child).toHaveBeenCalledWith({ + headers: { foo: 'bar' }, }); }); @@ -172,13 +143,11 @@ describe('ClusterClient', () => { const clusterClient = new ClusterClient(config, logger, getAuthHeaders); const request = httpServerMock.createKibanaRequest({}); - getClientFacadeMock.mockClear(); - clusterClient.asScoped(request); - expect(getClientFacadeMock).toHaveBeenCalledTimes(1); - expect(getClientFacadeMock).toHaveBeenCalledWith(scopedClient, { - authorization: 'auth', + expect(scopedClient.child).toHaveBeenCalledTimes(1); + expect(scopedClient.child).toHaveBeenCalledWith({ + headers: { authorization: 'auth' }, }); }); @@ -198,13 +167,87 @@ describe('ClusterClient', () => { }, }); - getClientFacadeMock.mockClear(); + clusterClient.asScoped(request); + + expect(scopedClient.child).toHaveBeenCalledTimes(1); + expect(scopedClient.child).toHaveBeenCalledWith({ + headers: { authorization: 'auth' }, + }); + }); + + it('includes the `customHeaders` from the config when creating the child client', () => { + const config = createConfig({ + customHeaders: { + foo: 'bar', + hello: 'dolly', + }, + requestHeadersWhitelist: ['authorization'], + }); + getAuthHeaders.mockReturnValue({}); + + const clusterClient = new ClusterClient(config, logger, getAuthHeaders); + const request = httpServerMock.createKibanaRequest({}); clusterClient.asScoped(request); - expect(getClientFacadeMock).toHaveBeenCalledTimes(1); - expect(getClientFacadeMock).toHaveBeenCalledWith(scopedClient, { - authorization: 'auth', + expect(scopedClient.child).toHaveBeenCalledTimes(1); + expect(scopedClient.child).toHaveBeenCalledWith({ + headers: { + foo: 'bar', + hello: 'dolly', + }, + }); + }); + + it('respect the precedence of auth headers over config headers', () => { + const config = createConfig({ + customHeaders: { + foo: 'config', + hello: 'dolly', + }, + requestHeadersWhitelist: ['foo'], + }); + getAuthHeaders.mockReturnValue({ + foo: 'auth', + }); + + const clusterClient = new ClusterClient(config, logger, getAuthHeaders); + const request = httpServerMock.createKibanaRequest({}); + + clusterClient.asScoped(request); + + expect(scopedClient.child).toHaveBeenCalledTimes(1); + expect(scopedClient.child).toHaveBeenCalledWith({ + headers: { + foo: 'auth', + hello: 'dolly', + }, + }); + }); + + it('respect the precedence of request headers over config headers', () => { + const config = createConfig({ + customHeaders: { + foo: 'config', + hello: 'dolly', + }, + requestHeadersWhitelist: ['foo'], + }); + getAuthHeaders.mockReturnValue({}); + + const clusterClient = new ClusterClient(config, logger, getAuthHeaders); + const request = httpServerMock.createKibanaRequest({ + headers: { foo: 'request' }, + }); + + clusterClient.asScoped(request); + + expect(scopedClient.child).toHaveBeenCalledTimes(1); + expect(scopedClient.child).toHaveBeenCalledWith({ + headers: { + foo: 'request', + hello: 'dolly', + }, }); }); @@ -222,13 +265,11 @@ describe('ClusterClient', () => { }, }; - getClientFacadeMock.mockClear(); - clusterClient.asScoped(request); - expect(getClientFacadeMock).toHaveBeenCalledTimes(1); - expect(getClientFacadeMock).toHaveBeenCalledWith(scopedClient, { - authorization: 'auth', + expect(scopedClient.child).toHaveBeenCalledTimes(1); + expect(scopedClient.child).toHaveBeenCalledWith({ + headers: { authorization: 'auth' }, }); }); @@ -248,13 +289,11 @@ describe('ClusterClient', () => { }, }; - getClientFacadeMock.mockClear(); - clusterClient.asScoped(request); - expect(getClientFacadeMock).toHaveBeenCalledTimes(1); - expect(getClientFacadeMock).toHaveBeenCalledWith(scopedClient, { - foo: 'bar', + expect(scopedClient.child).toHaveBeenCalledTimes(1); + expect(scopedClient.child).toHaveBeenCalledWith({ + headers: { foo: 'bar' }, }); }); }); diff --git a/src/core/server/elasticsearch/client/cluster_client.ts b/src/core/server/elasticsearch/client/cluster_client.ts index fae0be98ee0e8..0638efc1d8133 100644 --- a/src/core/server/elasticsearch/client/cluster_client.ts +++ b/src/core/server/elasticsearch/client/cluster_client.ts @@ -22,8 +22,7 @@ import { Logger } from '../../logging'; import { GetAuthHeaders, isRealRequest, Headers } from '../../http'; import { ensureRawRequest, filterHeaders } from '../../http/router'; import { ScopeableRequest } from '../types'; -import { getClientFacade } from './get_client_facade'; -import { ClientFacade } from './client_facade'; +import { ElasticSearchClient } from './types'; import { configureClient } from './configure_client'; import { ElasticsearchClientConfig } from './client_config'; import { ScopedClusterClient, IScopedClusterClient } from './scoped_cluster_client'; @@ -39,9 +38,9 @@ const noop = () => undefined; **/ export interface IClusterClient { /** - * Returns a {@link ClientFacade | facade} to be used to query the ES cluster on behalf of the Kibana internal user + * Returns a {@link ElasticSearchClient | client} to be used to query the ES cluster on behalf of the Kibana internal user */ - asInternalUser: () => ClientFacade; + asInternalUser: () => ElasticSearchClient; /** * Creates a {@link IScopedClusterClient | scoped cluster client} bound to given {@link ScopeableRequest | request} */ @@ -64,9 +63,8 @@ export interface ICustomClusterClient extends IClusterClient { /** @internal **/ export class ClusterClient implements IClusterClient, ICustomClusterClient { private readonly internalClient: Client; - private readonly scopedClient: Client; + private readonly rootScopedClient: Client; - private readonly internalFacade: ClientFacade; private isClosed = false; constructor( @@ -75,18 +73,19 @@ export class ClusterClient implements IClusterClient, ICustomClusterClient { private readonly getAuthHeaders: GetAuthHeaders = noop ) { this.internalClient = configureClient(config, { logger }); - this.internalFacade = getClientFacade(this.internalClient); - this.scopedClient = configureClient(config, { logger, scoped: true }); + this.rootScopedClient = configureClient(config, { logger, scoped: true }); } asInternalUser() { - return this.internalFacade; + return this.internalClient; } asScoped(request: ScopeableRequest) { - const headers = this.getScopedHeaders(request); - const scopedWrapper = getClientFacade(this.scopedClient, headers); - return new ScopedClusterClient(this.internalFacade, scopedWrapper); + const scopedHeaders = this.getScopedHeaders(request); + const scopedClient = this.rootScopedClient.child({ + headers: scopedHeaders, + }); + return new ScopedClusterClient(this.internalClient, scopedClient); } public close() { @@ -96,16 +95,25 @@ export class ClusterClient implements IClusterClient, ICustomClusterClient { this.isClosed = true; this.internalClient.close(); - this.scopedClient.close(); + this.rootScopedClient.close(); } private getScopedHeaders(request: ScopeableRequest): Headers { - if (!isRealRequest(request)) { - return filterHeaders(request?.headers ?? {}, this.config.requestHeadersWhitelist); + let scopedHeaders: Headers; + if (isRealRequest(request)) { + const authHeaders = this.getAuthHeaders(request); + const requestHeaders = ensureRawRequest(request).headers; + scopedHeaders = filterHeaders( + { ...requestHeaders, ...authHeaders }, + this.config.requestHeadersWhitelist + ); + } else { + scopedHeaders = filterHeaders(request?.headers ?? {}, this.config.requestHeadersWhitelist); } - const authHeaders = this.getAuthHeaders(request); - const headers = ensureRawRequest(request).headers; - return filterHeaders({ ...headers, ...authHeaders }, this.config.requestHeadersWhitelist); + return { + ...this.config.customHeaders, + ...scopedHeaders, + }; } } diff --git a/src/core/server/elasticsearch/client/get_client_facade.test.ts b/src/core/server/elasticsearch/client/get_client_facade.test.ts deleted file mode 100644 index 12160acfc435c..0000000000000 --- a/src/core/server/elasticsearch/client/get_client_facade.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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 '@elastic/elasticsearch'; -import { getClientFacade } from './get_client_facade'; - -// note this is only a partial version of the Client API -// as the facade is generated from our script, we can assume it is safe to -// only test behavior from arbitrary picked methods -// it also avoid to generate yet another file with a -// fully mocked `Client` interface -const getClientMock = (): DeeplyMockedKeys => { - return { - transport: { - request: jest.fn(), - }, - search: jest.fn(), - } as any; -}; - -describe('getClientFacade', () => { - let client: DeeplyMockedKeys; - - beforeEach(() => { - client = getClientMock(); - }); - - it('calls the client with correct parameters', () => { - const facade = getClientFacade(client, {}); - - facade.search({ from: 12, preference: 'pref' }, { maxRetries: 42 }); - - expect(client.search).toHaveBeenCalledTimes(1); - expect(client.search).toHaveBeenCalledWith( - { from: 12, preference: 'pref' }, - { maxRetries: 42, headers: {} } - ); - }); - - it('adds the facade headers to the `options.headers`', () => { - const facade = getClientFacade(client, { foo: 'bar', authorization: 'go' }); - - facade.search({}); - - expect(client.search).toHaveBeenCalledWith(expect.any(Object), { - headers: { foo: 'bar', authorization: 'go' }, - }); - }); - - it('respects the caller headers precedence', () => { - const facade = getClientFacade(client, { foo: 'facade', authorization: 'go' }); - - facade.search( - {}, - { - headers: { - foo: 'caller', - bar: 'true', - }, - } - ); - - expect(client.search).toHaveBeenCalledWith(expect.any(Object), { - headers: { - foo: 'caller', - authorization: 'go', - bar: 'true', - }, - }); - }); -}); diff --git a/src/core/server/elasticsearch/client/get_client_facade.ts b/src/core/server/elasticsearch/client/get_client_facade.ts deleted file mode 100644 index 8818fbf01390c..0000000000000 --- a/src/core/server/elasticsearch/client/get_client_facade.ts +++ /dev/null @@ -1,534 +0,0 @@ -/* - * 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 '@elastic/elasticsearch'; -import { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport'; -import { Headers } from '../../http/router'; -import { ClientFacade } from './client_facade'; - -/** - * Returns a {@link ClientFacade | facade} to be used to query given es client. - * - * This is used both for the internal client and the scoped ones. authorization header - * must be passed when creating a scoped facade. - * - * @internal - */ -export const getClientFacade = (client: Client, headers: Headers = {}): ClientFacade => { - // do not rename or change this method signature without adapting the API generation script - // at `src/dev/generate_es_client.ts` - const addHeaders = (options?: TransportRequestOptions): TransportRequestOptions => { - if (!options) { - return { - headers, - }; - } - return { - ...options, - headers: { - ...headers, - ...options.headers, - }, - }; - }; - - return { - transport: { - request: (params, options) => client.transport.request(params, addHeaders(options)), - }, - /* GENERATED */ - asyncSearch: { - delete: (params, options) => client.asyncSearch.delete(params, addHeaders(options)), - get: (params, options) => client.asyncSearch.get(params, addHeaders(options)), - submit: (params, options) => client.asyncSearch.submit(params, addHeaders(options)), - }, - autoscaling: { - deleteAutoscalingPolicy: (params, options) => - client.autoscaling.deleteAutoscalingPolicy(params, addHeaders(options)), - getAutoscalingDecision: (params, options) => - client.autoscaling.getAutoscalingDecision(params, addHeaders(options)), - getAutoscalingPolicy: (params, options) => - client.autoscaling.getAutoscalingPolicy(params, addHeaders(options)), - putAutoscalingPolicy: (params, options) => - client.autoscaling.putAutoscalingPolicy(params, addHeaders(options)), - }, - bulk: (params, options) => client.bulk(params, addHeaders(options)), - cat: { - aliases: (params, options) => client.cat.aliases(params, addHeaders(options)), - allocation: (params, options) => client.cat.allocation(params, addHeaders(options)), - count: (params, options) => client.cat.count(params, addHeaders(options)), - fielddata: (params, options) => client.cat.fielddata(params, addHeaders(options)), - health: (params, options) => client.cat.health(params, addHeaders(options)), - help: (params, options) => client.cat.help(params, addHeaders(options)), - indices: (params, options) => client.cat.indices(params, addHeaders(options)), - master: (params, options) => client.cat.master(params, addHeaders(options)), - mlDataFrameAnalytics: (params, options) => - client.cat.mlDataFrameAnalytics(params, addHeaders(options)), - mlDatafeeds: (params, options) => client.cat.mlDatafeeds(params, addHeaders(options)), - mlJobs: (params, options) => client.cat.mlJobs(params, addHeaders(options)), - mlTrainedModels: (params, options) => client.cat.mlTrainedModels(params, addHeaders(options)), - nodeattrs: (params, options) => client.cat.nodeattrs(params, addHeaders(options)), - nodes: (params, options) => client.cat.nodes(params, addHeaders(options)), - pendingTasks: (params, options) => client.cat.pendingTasks(params, addHeaders(options)), - plugins: (params, options) => client.cat.plugins(params, addHeaders(options)), - recovery: (params, options) => client.cat.recovery(params, addHeaders(options)), - repositories: (params, options) => client.cat.repositories(params, addHeaders(options)), - segments: (params, options) => client.cat.segments(params, addHeaders(options)), - shards: (params, options) => client.cat.shards(params, addHeaders(options)), - snapshots: (params, options) => client.cat.snapshots(params, addHeaders(options)), - tasks: (params, options) => client.cat.tasks(params, addHeaders(options)), - templates: (params, options) => client.cat.templates(params, addHeaders(options)), - threadPool: (params, options) => client.cat.threadPool(params, addHeaders(options)), - transforms: (params, options) => client.cat.transforms(params, addHeaders(options)), - }, - ccr: { - deleteAutoFollowPattern: (params, options) => - client.ccr.deleteAutoFollowPattern(params, addHeaders(options)), - follow: (params, options) => client.ccr.follow(params, addHeaders(options)), - followInfo: (params, options) => client.ccr.followInfo(params, addHeaders(options)), - followStats: (params, options) => client.ccr.followStats(params, addHeaders(options)), - forgetFollower: (params, options) => client.ccr.forgetFollower(params, addHeaders(options)), - getAutoFollowPattern: (params, options) => - client.ccr.getAutoFollowPattern(params, addHeaders(options)), - pauseAutoFollowPattern: (params, options) => - client.ccr.pauseAutoFollowPattern(params, addHeaders(options)), - pauseFollow: (params, options) => client.ccr.pauseFollow(params, addHeaders(options)), - putAutoFollowPattern: (params, options) => - client.ccr.putAutoFollowPattern(params, addHeaders(options)), - resumeAutoFollowPattern: (params, options) => - client.ccr.resumeAutoFollowPattern(params, addHeaders(options)), - resumeFollow: (params, options) => client.ccr.resumeFollow(params, addHeaders(options)), - stats: (params, options) => client.ccr.stats(params, addHeaders(options)), - unfollow: (params, options) => client.ccr.unfollow(params, addHeaders(options)), - }, - clearScroll: (params, options) => client.clearScroll(params, addHeaders(options)), - cluster: { - allocationExplain: (params, options) => - client.cluster.allocationExplain(params, addHeaders(options)), - deleteComponentTemplate: (params, options) => - client.cluster.deleteComponentTemplate(params, addHeaders(options)), - deleteVotingConfigExclusions: (params, options) => - client.cluster.deleteVotingConfigExclusions(params, addHeaders(options)), - existsComponentTemplate: (params, options) => - client.cluster.existsComponentTemplate(params, addHeaders(options)), - getComponentTemplate: (params, options) => - client.cluster.getComponentTemplate(params, addHeaders(options)), - getSettings: (params, options) => client.cluster.getSettings(params, addHeaders(options)), - health: (params, options) => client.cluster.health(params, addHeaders(options)), - pendingTasks: (params, options) => client.cluster.pendingTasks(params, addHeaders(options)), - postVotingConfigExclusions: (params, options) => - client.cluster.postVotingConfigExclusions(params, addHeaders(options)), - putComponentTemplate: (params, options) => - client.cluster.putComponentTemplate(params, addHeaders(options)), - putSettings: (params, options) => client.cluster.putSettings(params, addHeaders(options)), - remoteInfo: (params, options) => client.cluster.remoteInfo(params, addHeaders(options)), - reroute: (params, options) => client.cluster.reroute(params, addHeaders(options)), - state: (params, options) => client.cluster.state(params, addHeaders(options)), - stats: (params, options) => client.cluster.stats(params, addHeaders(options)), - }, - count: (params, options) => client.count(params, addHeaders(options)), - create: (params, options) => client.create(params, addHeaders(options)), - delete: (params, options) => client.delete(params, addHeaders(options)), - deleteByQuery: (params, options) => client.deleteByQuery(params, addHeaders(options)), - deleteByQueryRethrottle: (params, options) => - client.deleteByQueryRethrottle(params, addHeaders(options)), - deleteScript: (params, options) => client.deleteScript(params, addHeaders(options)), - enrich: { - deletePolicy: (params, options) => client.enrich.deletePolicy(params, addHeaders(options)), - executePolicy: (params, options) => client.enrich.executePolicy(params, addHeaders(options)), - getPolicy: (params, options) => client.enrich.getPolicy(params, addHeaders(options)), - putPolicy: (params, options) => client.enrich.putPolicy(params, addHeaders(options)), - stats: (params, options) => client.enrich.stats(params, addHeaders(options)), - }, - eql: { - search: (params, options) => client.eql.search(params, addHeaders(options)), - }, - exists: (params, options) => client.exists(params, addHeaders(options)), - existsSource: (params, options) => client.existsSource(params, addHeaders(options)), - explain: (params, options) => client.explain(params, addHeaders(options)), - fieldCaps: (params, options) => client.fieldCaps(params, addHeaders(options)), - get: (params, options) => client.get(params, addHeaders(options)), - getScript: (params, options) => client.getScript(params, addHeaders(options)), - getScriptContext: (params, options) => client.getScriptContext(params, addHeaders(options)), - getScriptLanguages: (params, options) => client.getScriptLanguages(params, addHeaders(options)), - getSource: (params, options) => client.getSource(params, addHeaders(options)), - graph: { - explore: (params, options) => client.graph.explore(params, addHeaders(options)), - }, - ilm: { - deleteLifecycle: (params, options) => client.ilm.deleteLifecycle(params, addHeaders(options)), - explainLifecycle: (params, options) => - client.ilm.explainLifecycle(params, addHeaders(options)), - getLifecycle: (params, options) => client.ilm.getLifecycle(params, addHeaders(options)), - getStatus: (params, options) => client.ilm.getStatus(params, addHeaders(options)), - moveToStep: (params, options) => client.ilm.moveToStep(params, addHeaders(options)), - putLifecycle: (params, options) => client.ilm.putLifecycle(params, addHeaders(options)), - removePolicy: (params, options) => client.ilm.removePolicy(params, addHeaders(options)), - retry: (params, options) => client.ilm.retry(params, addHeaders(options)), - start: (params, options) => client.ilm.start(params, addHeaders(options)), - stop: (params, options) => client.ilm.stop(params, addHeaders(options)), - }, - index: (params, options) => client.index(params, addHeaders(options)), - indices: { - analyze: (params, options) => client.indices.analyze(params, addHeaders(options)), - clearCache: (params, options) => client.indices.clearCache(params, addHeaders(options)), - clone: (params, options) => client.indices.clone(params, addHeaders(options)), - close: (params, options) => client.indices.close(params, addHeaders(options)), - create: (params, options) => client.indices.create(params, addHeaders(options)), - createDataStream: (params, options) => - client.indices.createDataStream(params, addHeaders(options)), - delete: (params, options) => client.indices.delete(params, addHeaders(options)), - deleteAlias: (params, options) => client.indices.deleteAlias(params, addHeaders(options)), - deleteDataStream: (params, options) => - client.indices.deleteDataStream(params, addHeaders(options)), - deleteIndexTemplate: (params, options) => - client.indices.deleteIndexTemplate(params, addHeaders(options)), - deleteTemplate: (params, options) => - client.indices.deleteTemplate(params, addHeaders(options)), - exists: (params, options) => client.indices.exists(params, addHeaders(options)), - existsAlias: (params, options) => client.indices.existsAlias(params, addHeaders(options)), - existsIndexTemplate: (params, options) => - client.indices.existsIndexTemplate(params, addHeaders(options)), - existsTemplate: (params, options) => - client.indices.existsTemplate(params, addHeaders(options)), - existsType: (params, options) => client.indices.existsType(params, addHeaders(options)), - flush: (params, options) => client.indices.flush(params, addHeaders(options)), - flushSynced: (params, options) => client.indices.flushSynced(params, addHeaders(options)), - forcemerge: (params, options) => client.indices.forcemerge(params, addHeaders(options)), - freeze: (params, options) => client.indices.freeze(params, addHeaders(options)), - get: (params, options) => client.indices.get(params, addHeaders(options)), - getAlias: (params, options) => client.indices.getAlias(params, addHeaders(options)), - getDataStreams: (params, options) => - client.indices.getDataStreams(params, addHeaders(options)), - getFieldMapping: (params, options) => - client.indices.getFieldMapping(params, addHeaders(options)), - getIndexTemplate: (params, options) => - client.indices.getIndexTemplate(params, addHeaders(options)), - getMapping: (params, options) => client.indices.getMapping(params, addHeaders(options)), - getSettings: (params, options) => client.indices.getSettings(params, addHeaders(options)), - getTemplate: (params, options) => client.indices.getTemplate(params, addHeaders(options)), - getUpgrade: (params, options) => client.indices.getUpgrade(params, addHeaders(options)), - open: (params, options) => client.indices.open(params, addHeaders(options)), - putAlias: (params, options) => client.indices.putAlias(params, addHeaders(options)), - putIndexTemplate: (params, options) => - client.indices.putIndexTemplate(params, addHeaders(options)), - putMapping: (params, options) => client.indices.putMapping(params, addHeaders(options)), - putSettings: (params, options) => client.indices.putSettings(params, addHeaders(options)), - putTemplate: (params, options) => client.indices.putTemplate(params, addHeaders(options)), - recovery: (params, options) => client.indices.recovery(params, addHeaders(options)), - refresh: (params, options) => client.indices.refresh(params, addHeaders(options)), - reloadSearchAnalyzers: (params, options) => - client.indices.reloadSearchAnalyzers(params, addHeaders(options)), - rollover: (params, options) => client.indices.rollover(params, addHeaders(options)), - segments: (params, options) => client.indices.segments(params, addHeaders(options)), - shardStores: (params, options) => client.indices.shardStores(params, addHeaders(options)), - shrink: (params, options) => client.indices.shrink(params, addHeaders(options)), - simulateIndexTemplate: (params, options) => - client.indices.simulateIndexTemplate(params, addHeaders(options)), - split: (params, options) => client.indices.split(params, addHeaders(options)), - stats: (params, options) => client.indices.stats(params, addHeaders(options)), - unfreeze: (params, options) => client.indices.unfreeze(params, addHeaders(options)), - updateAliases: (params, options) => client.indices.updateAliases(params, addHeaders(options)), - upgrade: (params, options) => client.indices.upgrade(params, addHeaders(options)), - validateQuery: (params, options) => client.indices.validateQuery(params, addHeaders(options)), - }, - info: (params, options) => client.info(params, addHeaders(options)), - ingest: { - deletePipeline: (params, options) => - client.ingest.deletePipeline(params, addHeaders(options)), - getPipeline: (params, options) => client.ingest.getPipeline(params, addHeaders(options)), - processorGrok: (params, options) => client.ingest.processorGrok(params, addHeaders(options)), - putPipeline: (params, options) => client.ingest.putPipeline(params, addHeaders(options)), - simulate: (params, options) => client.ingest.simulate(params, addHeaders(options)), - }, - license: { - delete: (params, options) => client.license.delete(params, addHeaders(options)), - get: (params, options) => client.license.get(params, addHeaders(options)), - getBasicStatus: (params, options) => - client.license.getBasicStatus(params, addHeaders(options)), - getTrialStatus: (params, options) => - client.license.getTrialStatus(params, addHeaders(options)), - post: (params, options) => client.license.post(params, addHeaders(options)), - postStartBasic: (params, options) => - client.license.postStartBasic(params, addHeaders(options)), - postStartTrial: (params, options) => - client.license.postStartTrial(params, addHeaders(options)), - }, - mget: (params, options) => client.mget(params, addHeaders(options)), - migration: { - deprecations: (params, options) => client.migration.deprecations(params, addHeaders(options)), - }, - ml: { - closeJob: (params, options) => client.ml.closeJob(params, addHeaders(options)), - deleteCalendar: (params, options) => client.ml.deleteCalendar(params, addHeaders(options)), - deleteCalendarEvent: (params, options) => - client.ml.deleteCalendarEvent(params, addHeaders(options)), - deleteCalendarJob: (params, options) => - client.ml.deleteCalendarJob(params, addHeaders(options)), - deleteDataFrameAnalytics: (params, options) => - client.ml.deleteDataFrameAnalytics(params, addHeaders(options)), - deleteDatafeed: (params, options) => client.ml.deleteDatafeed(params, addHeaders(options)), - deleteExpiredData: (params, options) => - client.ml.deleteExpiredData(params, addHeaders(options)), - deleteFilter: (params, options) => client.ml.deleteFilter(params, addHeaders(options)), - deleteForecast: (params, options) => client.ml.deleteForecast(params, addHeaders(options)), - deleteJob: (params, options) => client.ml.deleteJob(params, addHeaders(options)), - deleteModelSnapshot: (params, options) => - client.ml.deleteModelSnapshot(params, addHeaders(options)), - deleteTrainedModel: (params, options) => - client.ml.deleteTrainedModel(params, addHeaders(options)), - estimateModelMemory: (params, options) => - client.ml.estimateModelMemory(params, addHeaders(options)), - evaluateDataFrame: (params, options) => - client.ml.evaluateDataFrame(params, addHeaders(options)), - explainDataFrameAnalytics: (params, options) => - client.ml.explainDataFrameAnalytics(params, addHeaders(options)), - findFileStructure: (params, options) => - client.ml.findFileStructure(params, addHeaders(options)), - flushJob: (params, options) => client.ml.flushJob(params, addHeaders(options)), - forecast: (params, options) => client.ml.forecast(params, addHeaders(options)), - getBuckets: (params, options) => client.ml.getBuckets(params, addHeaders(options)), - getCalendarEvents: (params, options) => - client.ml.getCalendarEvents(params, addHeaders(options)), - getCalendars: (params, options) => client.ml.getCalendars(params, addHeaders(options)), - getCategories: (params, options) => client.ml.getCategories(params, addHeaders(options)), - getDataFrameAnalytics: (params, options) => - client.ml.getDataFrameAnalytics(params, addHeaders(options)), - getDataFrameAnalyticsStats: (params, options) => - client.ml.getDataFrameAnalyticsStats(params, addHeaders(options)), - getDatafeedStats: (params, options) => - client.ml.getDatafeedStats(params, addHeaders(options)), - getDatafeeds: (params, options) => client.ml.getDatafeeds(params, addHeaders(options)), - getFilters: (params, options) => client.ml.getFilters(params, addHeaders(options)), - getInfluencers: (params, options) => client.ml.getInfluencers(params, addHeaders(options)), - getJobStats: (params, options) => client.ml.getJobStats(params, addHeaders(options)), - getJobs: (params, options) => client.ml.getJobs(params, addHeaders(options)), - getModelSnapshots: (params, options) => - client.ml.getModelSnapshots(params, addHeaders(options)), - getOverallBuckets: (params, options) => - client.ml.getOverallBuckets(params, addHeaders(options)), - getRecords: (params, options) => client.ml.getRecords(params, addHeaders(options)), - getTrainedModels: (params, options) => - client.ml.getTrainedModels(params, addHeaders(options)), - getTrainedModelsStats: (params, options) => - client.ml.getTrainedModelsStats(params, addHeaders(options)), - info: (params, options) => client.ml.info(params, addHeaders(options)), - openJob: (params, options) => client.ml.openJob(params, addHeaders(options)), - postCalendarEvents: (params, options) => - client.ml.postCalendarEvents(params, addHeaders(options)), - postData: (params, options) => client.ml.postData(params, addHeaders(options)), - previewDatafeed: (params, options) => client.ml.previewDatafeed(params, addHeaders(options)), - putCalendar: (params, options) => client.ml.putCalendar(params, addHeaders(options)), - putCalendarJob: (params, options) => client.ml.putCalendarJob(params, addHeaders(options)), - putDataFrameAnalytics: (params, options) => - client.ml.putDataFrameAnalytics(params, addHeaders(options)), - putDatafeed: (params, options) => client.ml.putDatafeed(params, addHeaders(options)), - putFilter: (params, options) => client.ml.putFilter(params, addHeaders(options)), - putJob: (params, options) => client.ml.putJob(params, addHeaders(options)), - putTrainedModel: (params, options) => client.ml.putTrainedModel(params, addHeaders(options)), - revertModelSnapshot: (params, options) => - client.ml.revertModelSnapshot(params, addHeaders(options)), - setUpgradeMode: (params, options) => client.ml.setUpgradeMode(params, addHeaders(options)), - startDataFrameAnalytics: (params, options) => - client.ml.startDataFrameAnalytics(params, addHeaders(options)), - startDatafeed: (params, options) => client.ml.startDatafeed(params, addHeaders(options)), - stopDataFrameAnalytics: (params, options) => - client.ml.stopDataFrameAnalytics(params, addHeaders(options)), - stopDatafeed: (params, options) => client.ml.stopDatafeed(params, addHeaders(options)), - updateDatafeed: (params, options) => client.ml.updateDatafeed(params, addHeaders(options)), - updateFilter: (params, options) => client.ml.updateFilter(params, addHeaders(options)), - updateJob: (params, options) => client.ml.updateJob(params, addHeaders(options)), - updateModelSnapshot: (params, options) => - client.ml.updateModelSnapshot(params, addHeaders(options)), - validate: (params, options) => client.ml.validate(params, addHeaders(options)), - validateDetector: (params, options) => - client.ml.validateDetector(params, addHeaders(options)), - }, - monitoring: { - bulk: (params, options) => client.monitoring.bulk(params, addHeaders(options)), - }, - msearch: (params, options) => client.msearch(params, addHeaders(options)), - msearchTemplate: (params, options) => client.msearchTemplate(params, addHeaders(options)), - mtermvectors: (params, options) => client.mtermvectors(params, addHeaders(options)), - nodes: { - hotThreads: (params, options) => client.nodes.hotThreads(params, addHeaders(options)), - info: (params, options) => client.nodes.info(params, addHeaders(options)), - reloadSecureSettings: (params, options) => - client.nodes.reloadSecureSettings(params, addHeaders(options)), - stats: (params, options) => client.nodes.stats(params, addHeaders(options)), - usage: (params, options) => client.nodes.usage(params, addHeaders(options)), - }, - ping: (params, options) => client.ping(params, addHeaders(options)), - putScript: (params, options) => client.putScript(params, addHeaders(options)), - rankEval: (params, options) => client.rankEval(params, addHeaders(options)), - reindex: (params, options) => client.reindex(params, addHeaders(options)), - reindexRethrottle: (params, options) => client.reindexRethrottle(params, addHeaders(options)), - renderSearchTemplate: (params, options) => - client.renderSearchTemplate(params, addHeaders(options)), - rollup: { - deleteJob: (params, options) => client.rollup.deleteJob(params, addHeaders(options)), - getJobs: (params, options) => client.rollup.getJobs(params, addHeaders(options)), - getRollupCaps: (params, options) => client.rollup.getRollupCaps(params, addHeaders(options)), - getRollupIndexCaps: (params, options) => - client.rollup.getRollupIndexCaps(params, addHeaders(options)), - putJob: (params, options) => client.rollup.putJob(params, addHeaders(options)), - rollupSearch: (params, options) => client.rollup.rollupSearch(params, addHeaders(options)), - startJob: (params, options) => client.rollup.startJob(params, addHeaders(options)), - stopJob: (params, options) => client.rollup.stopJob(params, addHeaders(options)), - }, - scriptsPainlessExecute: (params, options) => - client.scriptsPainlessExecute(params, addHeaders(options)), - scroll: (params, options) => client.scroll(params, addHeaders(options)), - search: (params, options) => client.search(params, addHeaders(options)), - searchShards: (params, options) => client.searchShards(params, addHeaders(options)), - searchTemplate: (params, options) => client.searchTemplate(params, addHeaders(options)), - searchableSnapshots: { - clearCache: (params, options) => - client.searchableSnapshots.clearCache(params, addHeaders(options)), - mount: (params, options) => client.searchableSnapshots.mount(params, addHeaders(options)), - repositoryStats: (params, options) => - client.searchableSnapshots.repositoryStats(params, addHeaders(options)), - stats: (params, options) => client.searchableSnapshots.stats(params, addHeaders(options)), - }, - security: { - authenticate: (params, options) => client.security.authenticate(params, addHeaders(options)), - changePassword: (params, options) => - client.security.changePassword(params, addHeaders(options)), - clearCachedRealms: (params, options) => - client.security.clearCachedRealms(params, addHeaders(options)), - clearCachedRoles: (params, options) => - client.security.clearCachedRoles(params, addHeaders(options)), - createApiKey: (params, options) => client.security.createApiKey(params, addHeaders(options)), - deletePrivileges: (params, options) => - client.security.deletePrivileges(params, addHeaders(options)), - deleteRole: (params, options) => client.security.deleteRole(params, addHeaders(options)), - deleteRoleMapping: (params, options) => - client.security.deleteRoleMapping(params, addHeaders(options)), - deleteUser: (params, options) => client.security.deleteUser(params, addHeaders(options)), - disableUser: (params, options) => client.security.disableUser(params, addHeaders(options)), - enableUser: (params, options) => client.security.enableUser(params, addHeaders(options)), - getApiKey: (params, options) => client.security.getApiKey(params, addHeaders(options)), - getBuiltinPrivileges: (params, options) => - client.security.getBuiltinPrivileges(params, addHeaders(options)), - getPrivileges: (params, options) => - client.security.getPrivileges(params, addHeaders(options)), - getRole: (params, options) => client.security.getRole(params, addHeaders(options)), - getRoleMapping: (params, options) => - client.security.getRoleMapping(params, addHeaders(options)), - getToken: (params, options) => client.security.getToken(params, addHeaders(options)), - getUser: (params, options) => client.security.getUser(params, addHeaders(options)), - getUserPrivileges: (params, options) => - client.security.getUserPrivileges(params, addHeaders(options)), - hasPrivileges: (params, options) => - client.security.hasPrivileges(params, addHeaders(options)), - invalidateApiKey: (params, options) => - client.security.invalidateApiKey(params, addHeaders(options)), - invalidateToken: (params, options) => - client.security.invalidateToken(params, addHeaders(options)), - putPrivileges: (params, options) => - client.security.putPrivileges(params, addHeaders(options)), - putRole: (params, options) => client.security.putRole(params, addHeaders(options)), - putRoleMapping: (params, options) => - client.security.putRoleMapping(params, addHeaders(options)), - putUser: (params, options) => client.security.putUser(params, addHeaders(options)), - }, - slm: { - deleteLifecycle: (params, options) => client.slm.deleteLifecycle(params, addHeaders(options)), - executeLifecycle: (params, options) => - client.slm.executeLifecycle(params, addHeaders(options)), - executeRetention: (params, options) => - client.slm.executeRetention(params, addHeaders(options)), - getLifecycle: (params, options) => client.slm.getLifecycle(params, addHeaders(options)), - getStats: (params, options) => client.slm.getStats(params, addHeaders(options)), - getStatus: (params, options) => client.slm.getStatus(params, addHeaders(options)), - putLifecycle: (params, options) => client.slm.putLifecycle(params, addHeaders(options)), - start: (params, options) => client.slm.start(params, addHeaders(options)), - stop: (params, options) => client.slm.stop(params, addHeaders(options)), - }, - snapshot: { - cleanupRepository: (params, options) => - client.snapshot.cleanupRepository(params, addHeaders(options)), - create: (params, options) => client.snapshot.create(params, addHeaders(options)), - createRepository: (params, options) => - client.snapshot.createRepository(params, addHeaders(options)), - delete: (params, options) => client.snapshot.delete(params, addHeaders(options)), - deleteRepository: (params, options) => - client.snapshot.deleteRepository(params, addHeaders(options)), - get: (params, options) => client.snapshot.get(params, addHeaders(options)), - getRepository: (params, options) => - client.snapshot.getRepository(params, addHeaders(options)), - restore: (params, options) => client.snapshot.restore(params, addHeaders(options)), - status: (params, options) => client.snapshot.status(params, addHeaders(options)), - verifyRepository: (params, options) => - client.snapshot.verifyRepository(params, addHeaders(options)), - }, - sql: { - clearCursor: (params, options) => client.sql.clearCursor(params, addHeaders(options)), - query: (params, options) => client.sql.query(params, addHeaders(options)), - translate: (params, options) => client.sql.translate(params, addHeaders(options)), - }, - ssl: { - certificates: (params, options) => client.ssl.certificates(params, addHeaders(options)), - }, - tasks: { - cancel: (params, options) => client.tasks.cancel(params, addHeaders(options)), - get: (params, options) => client.tasks.get(params, addHeaders(options)), - list: (params, options) => client.tasks.list(params, addHeaders(options)), - }, - termvectors: (params, options) => client.termvectors(params, addHeaders(options)), - transform: { - deleteTransform: (params, options) => - client.transform.deleteTransform(params, addHeaders(options)), - getTransform: (params, options) => client.transform.getTransform(params, addHeaders(options)), - getTransformStats: (params, options) => - client.transform.getTransformStats(params, addHeaders(options)), - previewTransform: (params, options) => - client.transform.previewTransform(params, addHeaders(options)), - putTransform: (params, options) => client.transform.putTransform(params, addHeaders(options)), - startTransform: (params, options) => - client.transform.startTransform(params, addHeaders(options)), - stopTransform: (params, options) => - client.transform.stopTransform(params, addHeaders(options)), - updateTransform: (params, options) => - client.transform.updateTransform(params, addHeaders(options)), - }, - update: (params, options) => client.update(params, addHeaders(options)), - updateByQuery: (params, options) => client.updateByQuery(params, addHeaders(options)), - updateByQueryRethrottle: (params, options) => - client.updateByQueryRethrottle(params, addHeaders(options)), - watcher: { - ackWatch: (params, options) => client.watcher.ackWatch(params, addHeaders(options)), - activateWatch: (params, options) => client.watcher.activateWatch(params, addHeaders(options)), - deactivateWatch: (params, options) => - client.watcher.deactivateWatch(params, addHeaders(options)), - deleteWatch: (params, options) => client.watcher.deleteWatch(params, addHeaders(options)), - executeWatch: (params, options) => client.watcher.executeWatch(params, addHeaders(options)), - getWatch: (params, options) => client.watcher.getWatch(params, addHeaders(options)), - putWatch: (params, options) => client.watcher.putWatch(params, addHeaders(options)), - start: (params, options) => client.watcher.start(params, addHeaders(options)), - stats: (params, options) => client.watcher.stats(params, addHeaders(options)), - stop: (params, options) => client.watcher.stop(params, addHeaders(options)), - }, - xpack: { - info: (params, options) => client.xpack.info(params, addHeaders(options)), - usage: (params, options) => client.xpack.usage(params, addHeaders(options)), - }, - /* /GENERATED */ - }; -}; diff --git a/src/core/server/elasticsearch/client/index.ts b/src/core/server/elasticsearch/client/index.ts index 5a81f0e296e9b..1a2f1f013d69f 100644 --- a/src/core/server/elasticsearch/client/index.ts +++ b/src/core/server/elasticsearch/client/index.ts @@ -17,8 +17,8 @@ * under the License. */ +export { ElasticSearchClient } from './types'; export { IScopedClusterClient, ScopedClusterClient } from './scoped_cluster_client'; -export { ClientFacade } from './client_facade'; export { ElasticsearchClientConfig } from './client_config'; export { IClusterClient, ICustomClusterClient, ClusterClient } from './cluster_client'; export { configureClient } from './configure_client'; diff --git a/src/core/server/elasticsearch/client/mocks.test.ts b/src/core/server/elasticsearch/client/mocks.test.ts new file mode 100644 index 0000000000000..b882f8d0c5d79 --- /dev/null +++ b/src/core/server/elasticsearch/client/mocks.test.ts @@ -0,0 +1,60 @@ +/* + * 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 { elasticsearchClientMock } from './mocks'; + +describe('Mocked client', () => { + let client: ReturnType; + + const expectMocked = (fn: jest.MockedFunction | undefined) => { + expect(fn).toBeDefined(); + expect(fn.mockReturnValue).toEqual(expect.any(Function)); + }; + + beforeEach(() => { + client = elasticsearchClientMock.createInternalClient(); + }); + + it('`transport.request` should be mocked', () => { + expectMocked(client.transport.request); + }); + + it('root level API methods should be mocked', () => { + expectMocked(client.bulk); + expectMocked(client.search); + }); + + it('nested level API methods should be mocked', () => { + expectMocked(client.asyncSearch.get); + expectMocked(client.nodes.info); + }); + + it('`close` should be mocked', () => { + expectMocked(client.close); + }); + + it('`child` should be mocked and return a mocked Client', () => { + expectMocked(client.child); + + const child = client.child(); + + expect(child).not.toBe(client); + expectMocked(child.search); + }); +}); diff --git a/src/core/server/elasticsearch/client/mocks.ts b/src/core/server/elasticsearch/client/mocks.ts index 377830351eff5..2816389d003cd 100644 --- a/src/core/server/elasticsearch/client/mocks.ts +++ b/src/core/server/elasticsearch/client/mocks.ts @@ -17,20 +17,64 @@ * under the License. */ -import { ApiResponse } from '@elastic/elasticsearch'; +import { Client, ApiResponse } from '@elastic/elasticsearch'; import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport'; -import { clientFacadeMock } from './client_facade.mock'; +import { ElasticSearchClient } from './types'; import { IScopedClusterClient } from './scoped_cluster_client'; import { IClusterClient, ICustomClusterClient } from './cluster_client'; +const createInternalClientMock = (): DeeplyMockedKeys => { + // we mimic 'reflection' on a concrete instance of the client to generate the mocked functions. + const client = new Client({ + node: 'http://localhost', + }) as any; + + const blackListedProps = [ + '_events', + '_eventsCount', + '_maxListeners', + 'name', + 'serializer', + 'connectionPool', + 'transport', + 'helpers', + ]; + + const mockify = (obj: Record, blacklist: string[] = []) => { + Object.keys(obj) + .filter((key) => !blacklist.includes(key)) + .forEach((key) => { + const propType = typeof obj[key]; + if (propType === 'function') { + obj[key] = jest.fn(); + } else if (propType === 'object' && obj[key] != null) { + mockify(obj[key]); + } + }); + }; + + mockify(client, blackListedProps); + + client.transport = { + request: jest.fn(), + }; + client.close = jest.fn(); + client.child = jest.fn().mockImplementation(() => createInternalClientMock()); + + return (client as unknown) as DeeplyMockedKeys; +}; + +const createClientMock = (): DeeplyMockedKeys => + (createInternalClientMock() as unknown) as DeeplyMockedKeys; + const createScopedClusterClientMock = () => { const mock: jest.Mocked = { asInternalUser: jest.fn(), asCurrentUser: jest.fn(), }; - mock.asInternalUser.mockReturnValue(clientFacadeMock.create()); - mock.asCurrentUser.mockReturnValue(clientFacadeMock.create()); + mock.asInternalUser.mockReturnValue(createClientMock()); + mock.asCurrentUser.mockReturnValue(createClientMock()); return mock; }; @@ -41,7 +85,7 @@ const createClusterClientMock = () => { asScoped: jest.fn(), }; - mock.asInternalUser.mockReturnValue(clientFacadeMock.create()); + mock.asInternalUser.mockReturnValue(createClientMock()); mock.asScoped.mockReturnValue(createScopedClusterClientMock()); return mock; @@ -54,7 +98,7 @@ const createCustomClusterClientMock = () => { close: jest.fn(), }; - mock.asInternalUser.mockReturnValue(clientFacadeMock.create()); + mock.asInternalUser.mockReturnValue(createClientMock()); mock.asScoped.mockReturnValue(createScopedClusterClientMock()); return mock; @@ -88,7 +132,8 @@ export const elasticsearchClientMock = { createClusterClient: createClusterClientMock, createCustomClusterClient: createCustomClusterClientMock, createScopedClusterClient: createScopedClusterClientMock, - createFacade: clientFacadeMock.create, + createElasticSearchClient: createClientMock, + createInternalClient: createInternalClientMock, createClientResponse: createMockedClientResponse, createClientError: createMockedClientError, }; diff --git a/src/core/server/elasticsearch/client/scoped_cluster_client.test.ts b/src/core/server/elasticsearch/client/scoped_cluster_client.test.ts index c7d9b9ba9e303..ec5b92a2b2b99 100644 --- a/src/core/server/elasticsearch/client/scoped_cluster_client.test.ts +++ b/src/core/server/elasticsearch/client/scoped_cluster_client.test.ts @@ -22,8 +22,8 @@ import { ScopedClusterClient } from './scoped_cluster_client'; describe('ScopedClusterClient', () => { it('uses the internal client passed in the constructor', () => { - const internalClient = elasticsearchClientMock.createFacade(); - const scopedClient = elasticsearchClientMock.createFacade(); + const internalClient = elasticsearchClientMock.createElasticSearchClient(); + const scopedClient = elasticsearchClientMock.createElasticSearchClient(); const scopedClusterClient = new ScopedClusterClient(internalClient, scopedClient); @@ -31,8 +31,8 @@ describe('ScopedClusterClient', () => { }); it('uses the scoped client passed in the constructor', () => { - const internalClient = elasticsearchClientMock.createFacade(); - const scopedClient = elasticsearchClientMock.createFacade(); + const internalClient = elasticsearchClientMock.createElasticSearchClient(); + const scopedClient = elasticsearchClientMock.createElasticSearchClient(); const scopedClusterClient = new ScopedClusterClient(internalClient, scopedClient); diff --git a/src/core/server/elasticsearch/client/scoped_cluster_client.ts b/src/core/server/elasticsearch/client/scoped_cluster_client.ts index d0ed122bada69..2f30deedaf928 100644 --- a/src/core/server/elasticsearch/client/scoped_cluster_client.ts +++ b/src/core/server/elasticsearch/client/scoped_cluster_client.ts @@ -17,7 +17,7 @@ * under the License. */ -import { ClientFacade } from './client_facade'; +import { ElasticSearchClient } from './types'; /** * Serves the same purpose as the normal {@link ClusterClient | cluster client} but exposes @@ -29,22 +29,22 @@ import { ClientFacade } from './client_facade'; **/ export interface IScopedClusterClient { /** - * Returns a {@link ClientFacade | client facade} to be used to query the elasticsearch cluster + * Returns a {@link ElasticSearchClient | client} to be used to query the elasticsearch cluster * on behalf of the internal Kibana user. */ - asInternalUser: () => ClientFacade; + asInternalUser: () => ElasticSearchClient; /** - * Returns a {@link ClientFacade | client facade} to be used to query the elasticsearch cluster + * Returns a {@link ElasticSearchClient | client} to be used to query the elasticsearch cluster * on behalf of the user that initiated the request to the Kibana server. */ - asCurrentUser: () => ClientFacade; + asCurrentUser: () => ElasticSearchClient; } /** @internal **/ export class ScopedClusterClient implements IScopedClusterClient { constructor( - private readonly internalClient: ClientFacade, - private readonly scopedClient: ClientFacade + private readonly internalClient: ElasticSearchClient, + private readonly scopedClient: ElasticSearchClient ) {} asInternalUser() { diff --git a/scripts/generate_es_client.js b/src/core/server/elasticsearch/client/types.ts similarity index 59% rename from scripts/generate_es_client.js rename to src/core/server/elasticsearch/client/types.ts index 5d7845c933bff..6e93c2dddaa22 100644 --- a/scripts/generate_es_client.js +++ b/src/core/server/elasticsearch/client/types.ts @@ -17,5 +17,26 @@ * under the License. */ -require('../src/setup_node_env'); -require('../src/dev/generate_es_client'); +import type { Client } from '@elastic/elasticsearch'; +import type { + ApiResponse, + TransportRequestOptions, + TransportRequestParams, +} from '@elastic/elasticsearch/lib/Transport'; + +/** + * Client used to query the elasticsearch cluster. + * + * @public + */ +export type ElasticSearchClient = Omit< + Client, + 'connectionPool' | 'transport' | 'serializer' | 'extend' | 'helpers' | 'child' | 'close' +> & { + transport: { + request( + params: TransportRequestParams, + options?: TransportRequestOptions + ): Promise; + }; +}; diff --git a/src/core/server/elasticsearch/index.ts b/src/core/server/elasticsearch/index.ts index 4392aa61d2657..c5ee9f5e3d17b 100644 --- a/src/core/server/elasticsearch/index.ts +++ b/src/core/server/elasticsearch/index.ts @@ -34,6 +34,6 @@ export { IClusterClient, ICustomClusterClient, ElasticsearchClientConfig, - ClientFacade, + ElasticSearchClient, IScopedClusterClient, } from './client'; diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index da58c1129a6e1..0aecb61fc4453 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -4,7 +4,7 @@ ```ts -import { ApiResponse } from '@elastic/elasticsearch'; +import { ApiResponse } from '@elastic/elasticsearch/lib/Transport'; import Boom from 'boom'; import { BulkIndexDocumentsParams } from 'elasticsearch'; import { CatAliasesParams } from 'elasticsearch'; @@ -22,6 +22,7 @@ import { CatTasksParams } from 'elasticsearch'; import { CatThreadPoolParams } from 'elasticsearch'; import { ClearScrollParams } from 'elasticsearch'; import { Client } from 'elasticsearch'; +import { Client as Client_2 } from '@elastic/elasticsearch'; import { ClientOptions } from '@elastic/elasticsearch'; import { ClusterAllocationExplainParams } from 'elasticsearch'; import { ClusterGetSettingsParams } from 'elasticsearch'; @@ -115,9 +116,6 @@ import { ReindexParams } from 'elasticsearch'; import { ReindexRethrottleParams } from 'elasticsearch'; import { RenderSearchTemplateParams } from 'elasticsearch'; import { Request } from 'hapi'; -import { RequestBody } from '@elastic/elasticsearch/lib/Transport'; -import { RequestNDBody } from '@elastic/elasticsearch/lib/Transport'; -import * as RequestParams from '@elastic/elasticsearch/api/requestParams'; import { ResponseObject } from 'hapi'; import { ResponseToolkit } from 'hapi'; import { SchemaTypeError } from '@kbn/config-schema'; @@ -145,7 +143,6 @@ import { TasksListParams } from 'elasticsearch'; import { TermvectorsParams } from 'elasticsearch'; import { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport'; import { TransportRequestParams } from '@elastic/elasticsearch/lib/Transport'; -import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport'; import { Type } from '@kbn/config-schema'; import { TypeOf } from '@kbn/config-schema'; import { UpdateDocumentByQueryParams } from 'elasticsearch'; diff --git a/src/dev/generate_es_client.ts b/src/dev/generate_es_client.ts deleted file mode 100644 index 55a403d820d8b..0000000000000 --- a/src/dev/generate_es_client.ts +++ /dev/null @@ -1,151 +0,0 @@ -/* - * 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 { resolve, join } from 'path'; -import fs from 'fs'; - -const REPO_ROOT = resolve(__dirname, '../../'); -const GENERATION_START_SYMBOL = '/* GENERATED */'; -const GENERATION_END_SYMBOL = '/* /GENERATED */'; - -const sourceFile = join(REPO_ROOT, 'node_modules', '@elastic', 'elasticsearch', 'index.d.ts'); - -const targetFolder = join(REPO_ROOT, 'src', 'core', 'server', 'elasticsearch', 'client'); -const apiFile = join(targetFolder, 'client_facade.ts'); -const implemFile = join(targetFolder, 'get_client_facade.ts'); -const mockFile = join(targetFolder, 'client_facade.mock.ts'); - -const generate = () => { - const clientAPI = readClientAPI(); - const { api, impl, mock } = processClientAPI(clientAPI); - - writeFacadeAPI(api); - writeWrapperDefinition(impl); - writeMockDefinition(mock); - - // apply es-lint to the generated file - // as indentation may not be correct, and some of our lint rules are not respected by the es lib. - process.argv.push('--fix'); - process.argv.push(apiFile); - process.argv.push(implemFile); - process.argv.push(mockFile); - require('./run_eslint'); -}; - -const apiLineRegexp = /^([a-zA-Z_]*)[<]/; -const callbackApiRegexp = /TransportRequestCallback/; - -const blockStartRegexp = /^([a-zA-Z_]*)[:][ ][{]$/; -const blockEndRegexp = /^[}]$/; - -const processClientAPI = (rawContent: string) => { - const apiLines: string[] = []; - const implementationLines: string[] = []; - const mockLines: string[] = []; - - let currentBlock: string | null = null; - let inDeletedBlock = false; - - rawContent - .split('\n') - .map((line) => line.trim()) - .forEach((line) => { - const blockStartMatch = blockStartRegexp.exec(line); - - // start of a block of API, I.E : `asyncSearch: {` - if (blockStartMatch) { - currentBlock = blockStartMatch[1]; - if (currentBlock.includes('_')) { - inDeletedBlock = true; - } else { - // add `[blockName]: {` to both API and implementation - apiLines.push(line); - implementationLines.push(line); - mockLines.push(line); - } - } else if (blockEndRegexp.test(line)) { - if (!inDeletedBlock) { - apiLines.push('}'); - implementationLines.push('},'); - mockLines.push('},'); - } - currentBlock = null; - inDeletedBlock = false; - } else { - const isApiLineMatch = apiLineRegexp.exec(line); - const isCallbackApi = callbackApiRegexp.test(line); - if (isApiLineMatch && !isCallbackApi && !inDeletedBlock) { - const apiName = isApiLineMatch[1]; - if (!apiName.includes('_')) { - apiLines.push(line); - implementationLines.push( - `${apiName}: (params, options) => client${ - currentBlock ? '.' + currentBlock : '' - }.${apiName}(params, addHeaders(options)),` - ); - mockLines.push(`${apiName}: jest.fn(),`); - } - } - } - }); - - return { - api: apiLines.join('\n'), - impl: implementationLines.join('\n'), - mock: mockLines.join('\n'), - }; -}; - -const readClientAPI = (): string => { - const sourceFileContent = fs.readFileSync(sourceFile).toString('utf-8'); - return sourceFileContent.substring( - sourceFileContent.indexOf(GENERATION_START_SYMBOL) + GENERATION_START_SYMBOL.length, - sourceFileContent.indexOf(GENERATION_END_SYMBOL) - ); -}; - -const writeFacadeAPI = (apiDefinition: string) => { - injectGeneratedContent(apiFile, apiDefinition); -}; - -const writeWrapperDefinition = (implemDefinition: string) => { - injectGeneratedContent(implemFile, implemDefinition); -}; - -const writeMockDefinition = (mockDefinition: string) => { - injectGeneratedContent(mockFile, mockDefinition); -}; - -const injectGeneratedContent = (filepath: string, injectedContent: string) => { - const fileContent = fs.readFileSync(filepath, 'utf-8').toString(); - - const newFileContent = - fileContent.slice( - 0, - fileContent.indexOf(GENERATION_START_SYMBOL) + GENERATION_START_SYMBOL.length - ) + - `\n` + - injectedContent + - `\n` + - fileContent.slice(fileContent.indexOf(GENERATION_END_SYMBOL)); - - fs.writeFileSync(filepath, newFileContent); -}; - -generate(); From 56db6c43c7105078491240171438a1c707c4d732 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Fri, 3 Jul 2020 13:56:47 +0200 Subject: [PATCH 35/42] log queries even in case of error --- .../client/configure_client.test.ts | 39 +++++++++++++++++++ .../elasticsearch/client/configure_client.ts | 3 +- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/core/server/elasticsearch/client/configure_client.test.ts b/src/core/server/elasticsearch/client/configure_client.test.ts index fa9c3ecc4c295..ba61e940d601b 100644 --- a/src/core/server/elasticsearch/client/configure_client.test.ts +++ b/src/core/server/elasticsearch/client/configure_client.test.ts @@ -179,6 +179,45 @@ describe('configureClient', () => { `); }); + it('logs queries even in case of errors if `logQueries` is true', () => { + const client = configureClient( + createFakeConfig({ + logQueries: true, + }), + { logger, scoped: false } + ); + + const response = createApiResponse({ + statusCode: 500, + body: { + error: { + type: 'internal server error', + }, + }, + params: { + method: 'GET', + path: '/foo', + querystring: { hello: 'dolly' }, + }, + }); + client.emit('response', new errors.ResponseError(response), response); + + expect(loggingSystemMock.collect(logger).debug).toMatchInlineSnapshot(` + Array [ + Array [ + "500 + GET /foo + hello=dolly", + Object { + "tags": Array [ + "query", + ], + }, + ], + ] + `); + }); + it('does not log queries if `logQueries` is false', () => { const client = configureClient( createFakeConfig({ diff --git a/src/core/server/elasticsearch/client/configure_client.ts b/src/core/server/elasticsearch/client/configure_client.ts index 093c8363a8a16..5377f8ca1b070 100644 --- a/src/core/server/elasticsearch/client/configure_client.ts +++ b/src/core/server/elasticsearch/client/configure_client.ts @@ -38,7 +38,8 @@ const addLogging = (client: Client, logger: Logger, logQueries: boolean) => { client.on('response', (err, event) => { if (err) { logger.error(`${err.name}: ${err.message}`); - } else if (logQueries) { + } + if (event && logQueries) { const params = event.meta.request.params; // definition is wrong, `params.querystring` can be either a string or an object From d6f1c9dcdb63b50842072df070fbd525aa3d42c7 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Fri, 3 Jul 2020 13:59:50 +0200 Subject: [PATCH 36/42] nits --- .../server/elasticsearch/elasticsearch_service.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/core/server/elasticsearch/elasticsearch_service.ts b/src/core/server/elasticsearch/elasticsearch_service.ts index 10fce9ec3c021..c7f145c7d3df1 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.ts @@ -56,10 +56,6 @@ export class ElasticsearchService private legacyClient?: LegacyClusterClient; private client?: ClusterClient; - private createCustomClient?: ( - type: string, - clientConfig?: Partial - ) => ICustomClusterClient; constructor(private readonly coreContext: CoreContext) { this.kibanaVersion = coreContext.env.packageInfo.version; @@ -107,14 +103,18 @@ export class ElasticsearchService const config = await this.config$.pipe(first()).toPromise(); this.client = this.createClusterClient('data', config); - this.createCustomClient = (type, clientConfig = {}) => { + + const createClient = ( + type: string, + clientConfig: Partial = {} + ): ICustomClusterClient => { const finalConfig = merge({}, config, clientConfig); return this.createClusterClient(type, finalConfig); }; return { client: this.client, - createClient: this.createCustomClient, + createClient, legacy: { client: this.legacyClient, createClient: this.createLegacyCustomClient, From 83b72462453d2dada9425ce8cb460da5282cc059 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Fri, 3 Jul 2020 15:00:39 +0200 Subject: [PATCH 37/42] use direct properties instead of accessors --- .../client/cluster_client.test.ts | 8 ++-- .../elasticsearch/client/cluster_client.ts | 16 +++---- src/core/server/elasticsearch/client/mocks.ts | 42 +++++++++++-------- .../client/scoped_cluster_client.test.ts | 4 +- .../client/scoped_cluster_client.ts | 20 +++------ .../elasticsearch_service.mock.ts | 11 +++-- .../elasticsearch_service.test.ts | 4 +- 7 files changed, 51 insertions(+), 54 deletions(-) diff --git a/src/core/server/elasticsearch/client/cluster_client.test.ts b/src/core/server/elasticsearch/client/cluster_client.test.ts index 0d2274b67e8fe..5bb0943d4a5a9 100644 --- a/src/core/server/elasticsearch/client/cluster_client.test.ts +++ b/src/core/server/elasticsearch/client/cluster_client.test.ts @@ -78,7 +78,7 @@ describe('ClusterClient', () => { it('returns the internal client', () => { const clusterClient = new ClusterClient(createConfig(), logger, getAuthHeaders); - expect(clusterClient.asInternalUser()).toBe(internalClient); + expect(clusterClient.asInternalUser).toBe(internalClient); }); }); @@ -92,8 +92,8 @@ describe('ClusterClient', () => { expect(scopedClient.child).toHaveBeenCalledTimes(1); expect(scopedClient.child).toHaveBeenCalledWith({ headers: expect.any(Object) }); - expect(scopedClusterClient.asInternalUser()).toBe(clusterClient.asInternalUser()); - expect(scopedClusterClient.asCurrentUser()).toBe(scopedClient.child.mock.results[0].value); + expect(scopedClusterClient.asInternalUser).toBe(clusterClient.asInternalUser); + expect(scopedClusterClient.asCurrentUser).toBe(scopedClient.child.mock.results[0].value); }); it('returns a distinct scoped cluster client on each call', () => { @@ -106,7 +106,7 @@ describe('ClusterClient', () => { expect(scopedClient.child).toHaveBeenCalledTimes(2); expect(scopedClusterClient1).not.toBe(scopedClusterClient2); - expect(scopedClusterClient1.asInternalUser()).toBe(scopedClusterClient2.asInternalUser()); + expect(scopedClusterClient1.asInternalUser).toBe(scopedClusterClient2.asInternalUser); }); it('creates a scoped client with filtered request headers', () => { diff --git a/src/core/server/elasticsearch/client/cluster_client.ts b/src/core/server/elasticsearch/client/cluster_client.ts index 0638efc1d8133..e6ed9fb48ec0a 100644 --- a/src/core/server/elasticsearch/client/cluster_client.ts +++ b/src/core/server/elasticsearch/client/cluster_client.ts @@ -38,9 +38,9 @@ const noop = () => undefined; **/ export interface IClusterClient { /** - * Returns a {@link ElasticSearchClient | client} to be used to query the ES cluster on behalf of the Kibana internal user + * A {@link ElasticSearchClient | client} to be used to query the ES cluster on behalf of the Kibana internal user */ - asInternalUser: () => ElasticSearchClient; + readonly asInternalUser: ElasticSearchClient; /** * Creates a {@link IScopedClusterClient | scoped cluster client} bound to given {@link ScopeableRequest | request} */ @@ -62,7 +62,7 @@ export interface ICustomClusterClient extends IClusterClient { /** @internal **/ export class ClusterClient implements IClusterClient, ICustomClusterClient { - private readonly internalClient: Client; + public readonly asInternalUser: Client; private readonly rootScopedClient: Client; private isClosed = false; @@ -72,20 +72,16 @@ export class ClusterClient implements IClusterClient, ICustomClusterClient { logger: Logger, private readonly getAuthHeaders: GetAuthHeaders = noop ) { - this.internalClient = configureClient(config, { logger }); + this.asInternalUser = configureClient(config, { logger }); this.rootScopedClient = configureClient(config, { logger, scoped: true }); } - asInternalUser() { - return this.internalClient; - } - asScoped(request: ScopeableRequest) { const scopedHeaders = this.getScopedHeaders(request); const scopedClient = this.rootScopedClient.child({ headers: scopedHeaders, }); - return new ScopedClusterClient(this.internalClient, scopedClient); + return new ScopedClusterClient(this.asInternalUser, scopedClient); } public close() { @@ -94,7 +90,7 @@ export class ClusterClient implements IClusterClient, ICustomClusterClient { } this.isClosed = true; - this.internalClient.close(); + this.asInternalUser.close(); this.rootScopedClient.close(); } diff --git a/src/core/server/elasticsearch/client/mocks.ts b/src/core/server/elasticsearch/client/mocks.ts index 2816389d003cd..c31280c9a53d9 100644 --- a/src/core/server/elasticsearch/client/mocks.ts +++ b/src/core/server/elasticsearch/client/mocks.ts @@ -20,8 +20,7 @@ import { Client, ApiResponse } from '@elastic/elasticsearch'; import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport'; import { ElasticSearchClient } from './types'; -import { IScopedClusterClient } from './scoped_cluster_client'; -import { IClusterClient, ICustomClusterClient } from './cluster_client'; +import { ICustomClusterClient } from './cluster_client'; const createInternalClientMock = (): DeeplyMockedKeys => { // we mimic 'reflection' on a concrete instance of the client to generate the mocked functions. @@ -64,47 +63,56 @@ const createInternalClientMock = (): DeeplyMockedKeys => { return (client as unknown) as DeeplyMockedKeys; }; -const createClientMock = (): DeeplyMockedKeys => - (createInternalClientMock() as unknown) as DeeplyMockedKeys; +export type ElasticSearchClientMock = DeeplyMockedKeys; + +const createClientMock = (): ElasticSearchClientMock => + (createInternalClientMock() as unknown) as ElasticSearchClientMock; + +interface ScopedClusterClientMock { + asInternalUser: ElasticSearchClientMock; + asCurrentUser: ElasticSearchClientMock; +} const createScopedClusterClientMock = () => { - const mock: jest.Mocked = { - asInternalUser: jest.fn(), - asCurrentUser: jest.fn(), + const mock: ScopedClusterClientMock = { + asInternalUser: createClientMock(), + asCurrentUser: createClientMock(), }; - mock.asInternalUser.mockReturnValue(createClientMock()); - mock.asCurrentUser.mockReturnValue(createClientMock()); - return mock; }; +export interface ClusterClientMock { + asInternalUser: ElasticSearchClientMock; + asScoped: jest.MockedFunction<() => ScopedClusterClientMock>; +} + const createClusterClientMock = () => { - const mock: jest.Mocked = { - asInternalUser: jest.fn(), + const mock: ClusterClientMock = { + asInternalUser: createClientMock(), asScoped: jest.fn(), }; - mock.asInternalUser.mockReturnValue(createClientMock()); mock.asScoped.mockReturnValue(createScopedClusterClientMock()); return mock; }; +export type CustomClusterClientMock = jest.Mocked & ClusterClientMock; + const createCustomClusterClientMock = () => { - const mock: jest.Mocked = { - asInternalUser: jest.fn(), + const mock: CustomClusterClientMock = { + asInternalUser: createClientMock(), asScoped: jest.fn(), close: jest.fn(), }; - mock.asInternalUser.mockReturnValue(createClientMock()); mock.asScoped.mockReturnValue(createScopedClusterClientMock()); return mock; }; -type MockedTransportRequestPromise = TransportRequestPromise & { +export type MockedTransportRequestPromise = TransportRequestPromise & { abort: jest.MockedFunction<() => undefined>; }; diff --git a/src/core/server/elasticsearch/client/scoped_cluster_client.test.ts b/src/core/server/elasticsearch/client/scoped_cluster_client.test.ts index ec5b92a2b2b99..78ca8fcbd3c07 100644 --- a/src/core/server/elasticsearch/client/scoped_cluster_client.test.ts +++ b/src/core/server/elasticsearch/client/scoped_cluster_client.test.ts @@ -27,7 +27,7 @@ describe('ScopedClusterClient', () => { const scopedClusterClient = new ScopedClusterClient(internalClient, scopedClient); - expect(scopedClusterClient.asInternalUser()).toBe(internalClient); + expect(scopedClusterClient.asInternalUser).toBe(internalClient); }); it('uses the scoped client passed in the constructor', () => { @@ -36,6 +36,6 @@ describe('ScopedClusterClient', () => { const scopedClusterClient = new ScopedClusterClient(internalClient, scopedClient); - expect(scopedClusterClient.asCurrentUser()).toBe(scopedClient); + expect(scopedClusterClient.asCurrentUser).toBe(scopedClient); }); }); diff --git a/src/core/server/elasticsearch/client/scoped_cluster_client.ts b/src/core/server/elasticsearch/client/scoped_cluster_client.ts index 2f30deedaf928..51a51db190c2d 100644 --- a/src/core/server/elasticsearch/client/scoped_cluster_client.ts +++ b/src/core/server/elasticsearch/client/scoped_cluster_client.ts @@ -29,29 +29,21 @@ import { ElasticSearchClient } from './types'; **/ export interface IScopedClusterClient { /** - * Returns a {@link ElasticSearchClient | client} to be used to query the elasticsearch cluster + * A {@link ElasticSearchClient | client} to be used to query the elasticsearch cluster * on behalf of the internal Kibana user. */ - asInternalUser: () => ElasticSearchClient; + readonly asInternalUser: ElasticSearchClient; /** - * Returns a {@link ElasticSearchClient | client} to be used to query the elasticsearch cluster + * A {@link ElasticSearchClient | client} to be used to query the elasticsearch cluster * on behalf of the user that initiated the request to the Kibana server. */ - asCurrentUser: () => ElasticSearchClient; + readonly asCurrentUser: ElasticSearchClient; } /** @internal **/ export class ScopedClusterClient implements IScopedClusterClient { constructor( - private readonly internalClient: ElasticSearchClient, - private readonly scopedClient: ElasticSearchClient + public readonly asInternalUser: ElasticSearchClient, + public readonly asCurrentUser: ElasticSearchClient ) {} - - asInternalUser() { - return this.internalClient; - } - - asCurrentUser() { - return this.scopedClient; - } } diff --git a/src/core/server/elasticsearch/elasticsearch_service.mock.ts b/src/core/server/elasticsearch/elasticsearch_service.mock.ts index de2ab34456e52..816a37484b329 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.mock.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.mock.ts @@ -19,8 +19,11 @@ import { BehaviorSubject } from 'rxjs'; import { ILegacyClusterClient, ILegacyCustomClusterClient } from './legacy'; -import { IClusterClient, ICustomClusterClient } from './client'; -import { elasticsearchClientMock } from './client/mocks'; +import { + elasticsearchClientMock, + ClusterClientMock, + CustomClusterClientMock, +} from './client/mocks'; import { legacyClientMock } from './legacy/mocks'; import { ElasticsearchConfig } from './elasticsearch_config'; import { ElasticsearchService } from './elasticsearch_service'; @@ -38,8 +41,8 @@ interface MockedElasticSearchServiceSetup { type MockedElasticSearchServiceStart = MockedElasticSearchServiceSetup; interface MockedInternalElasticSearchServiceStart extends MockedElasticSearchServiceStart { - client: jest.Mocked; - createClient: jest.Mock; + client: ClusterClientMock; + createClient: jest.MockedFunction<() => CustomClusterClientMock>; } const createSetupContractMock = () => { diff --git a/src/core/server/elasticsearch/elasticsearch_service.test.ts b/src/core/server/elasticsearch/elasticsearch_service.test.ts index b0a76ee6e1509..dec558fcf1bb1 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.test.ts @@ -261,9 +261,7 @@ describe('#start', () => { const startContract = await elasticsearchService.start(); const client = startContract.client; - expect(client.asInternalUser).toHaveBeenCalledTimes(0); - client.asInternalUser(); - expect(mockClusterClientInstance.asInternalUser).toHaveBeenCalledTimes(1); + expect(client.asInternalUser).toBe(mockClusterClientInstance.asInternalUser); }); describe('#createClient', () => { From a764b10db4343b0ac799eb4260aa7dd4baccf390 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Fri, 3 Jul 2020 17:08:37 +0200 Subject: [PATCH 38/42] handle async closing of client --- .../client/cluster_client.test.ts | 62 +++++++++++++++++-- .../elasticsearch/client/cluster_client.ts | 8 +-- src/core/server/elasticsearch/client/mocks.ts | 3 +- 3 files changed, 61 insertions(+), 12 deletions(-) diff --git a/src/core/server/elasticsearch/client/cluster_client.test.ts b/src/core/server/elasticsearch/client/cluster_client.test.ts index 5bb0943d4a5a9..e524dfc9b3003 100644 --- a/src/core/server/elasticsearch/client/cluster_client.test.ts +++ b/src/core/server/elasticsearch/client/cluster_client.test.ts @@ -299,25 +299,75 @@ describe('ClusterClient', () => { }); describe('#close', () => { - it('closes both underlying clients', () => { + it('closes both underlying clients', async () => { const clusterClient = new ClusterClient(createConfig(), logger, getAuthHeaders); - clusterClient.close(); + await clusterClient.close(); expect(internalClient.close).toHaveBeenCalledTimes(1); expect(scopedClient.close).toHaveBeenCalledTimes(1); }); - it('does nothing after the first call', () => { + it('waits for both clients to close', async (done) => { + expect.assertions(4); + + const clusterClient = new ClusterClient(createConfig(), logger, getAuthHeaders); + + let internalClientClosed = false; + let scopedClientClosed = false; + let clusterClientClosed = false; + + let closeInternalClient: () => void; + let closeScopedClient: () => void; + + internalClient.close.mockReturnValue( + new Promise((resolve) => { + closeInternalClient = resolve; + }).then(() => { + expect(clusterClientClosed).toBe(false); + internalClientClosed = true; + }) + ); + scopedClient.close.mockReturnValue( + new Promise((resolve) => { + closeScopedClient = resolve; + }).then(() => { + expect(clusterClientClosed).toBe(false); + scopedClientClosed = true; + }) + ); + + clusterClient.close().then(() => { + clusterClientClosed = true; + expect(internalClientClosed).toBe(true); + expect(scopedClientClosed).toBe(true); + done(); + }); + + closeInternalClient!(); + closeScopedClient!(); + }); + + it('return a rejected promise is any client rejects', async () => { + const clusterClient = new ClusterClient(createConfig(), logger, getAuthHeaders); + + internalClient.close.mockRejectedValue(new Error('error closing client')); + + expect(clusterClient.close()).rejects.toThrowErrorMatchingInlineSnapshot( + `"error closing client"` + ); + }); + + it('does nothing after the first call', async () => { const clusterClient = new ClusterClient(createConfig(), logger, getAuthHeaders); - clusterClient.close(); + await clusterClient.close(); expect(internalClient.close).toHaveBeenCalledTimes(1); expect(scopedClient.close).toHaveBeenCalledTimes(1); - clusterClient.close(); - clusterClient.close(); + await clusterClient.close(); + await clusterClient.close(); expect(internalClient.close).toHaveBeenCalledTimes(1); expect(scopedClient.close).toHaveBeenCalledTimes(1); diff --git a/src/core/server/elasticsearch/client/cluster_client.ts b/src/core/server/elasticsearch/client/cluster_client.ts index e6ed9fb48ec0a..2378bf443a3fb 100644 --- a/src/core/server/elasticsearch/client/cluster_client.ts +++ b/src/core/server/elasticsearch/client/cluster_client.ts @@ -57,7 +57,7 @@ export interface ICustomClusterClient extends IClusterClient { * Closes the cluster client. After that client cannot be used and one should * create a new client instance to be able to interact with Elasticsearch API. */ - close: () => void; + close: () => Promise; } /** @internal **/ @@ -84,14 +84,12 @@ export class ClusterClient implements IClusterClient, ICustomClusterClient { return new ScopedClusterClient(this.asInternalUser, scopedClient); } - public close() { + public async close() { if (this.isClosed) { return; } - this.isClosed = true; - this.asInternalUser.close(); - this.rootScopedClient.close(); + await Promise.all([this.asInternalUser.close(), this.rootScopedClient.close()]); } private getScopedHeaders(request: ScopeableRequest): Headers { diff --git a/src/core/server/elasticsearch/client/mocks.ts b/src/core/server/elasticsearch/client/mocks.ts index c31280c9a53d9..36cc27a5ba3ee 100644 --- a/src/core/server/elasticsearch/client/mocks.ts +++ b/src/core/server/elasticsearch/client/mocks.ts @@ -57,7 +57,7 @@ const createInternalClientMock = (): DeeplyMockedKeys => { client.transport = { request: jest.fn(), }; - client.close = jest.fn(); + client.close = jest.fn().mockReturnValue(Promise.resolve()); client.child = jest.fn().mockImplementation(() => createInternalClientMock()); return (client as unknown) as DeeplyMockedKeys; @@ -108,6 +108,7 @@ const createCustomClusterClientMock = () => { }; mock.asScoped.mockReturnValue(createScopedClusterClientMock()); + mock.close.mockReturnValue(Promise.resolve()); return mock; }; From 413a97d222b6a4a0c85d66ad2edb3c113cb920fd Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 7 Jul 2020 12:52:56 +0200 Subject: [PATCH 39/42] review nits --- src/core/server/elasticsearch/client/cluster_client.test.ts | 2 +- src/core/server/elasticsearch/client/cluster_client.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/server/elasticsearch/client/cluster_client.test.ts b/src/core/server/elasticsearch/client/cluster_client.test.ts index e524dfc9b3003..85517b80745f1 100644 --- a/src/core/server/elasticsearch/client/cluster_client.test.ts +++ b/src/core/server/elasticsearch/client/cluster_client.test.ts @@ -175,7 +175,7 @@ describe('ClusterClient', () => { }); }); - it('includes the `customHeaders` from the config when creating the child client', () => { + it('includes the `customHeaders` from the config without filtering them', () => { const config = createConfig({ customHeaders: { foo: 'bar', diff --git a/src/core/server/elasticsearch/client/cluster_client.ts b/src/core/server/elasticsearch/client/cluster_client.ts index 2378bf443a3fb..09b577088e8a3 100644 --- a/src/core/server/elasticsearch/client/cluster_client.ts +++ b/src/core/server/elasticsearch/client/cluster_client.ts @@ -61,7 +61,7 @@ export interface ICustomClusterClient extends IClusterClient { } /** @internal **/ -export class ClusterClient implements IClusterClient, ICustomClusterClient { +export class ClusterClient implements ICustomClusterClient { public readonly asInternalUser: Client; private readonly rootScopedClient: Client; From c0d7f3a331bff91d94089485393e75bbc82a7843 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 7 Jul 2020 13:17:02 +0200 Subject: [PATCH 40/42] ElasticSearchClient -> ElasticsearchClient --- .../server/elasticsearch/client/cluster_client.ts | 6 +++--- src/core/server/elasticsearch/client/index.ts | 2 +- src/core/server/elasticsearch/client/mocks.ts | 4 ++-- .../elasticsearch/client/scoped_cluster_client.ts | 14 +++++++------- src/core/server/elasticsearch/client/types.ts | 2 +- src/core/server/elasticsearch/index.ts | 2 +- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/core/server/elasticsearch/client/cluster_client.ts b/src/core/server/elasticsearch/client/cluster_client.ts index 09b577088e8a3..d9a0e6fe3f238 100644 --- a/src/core/server/elasticsearch/client/cluster_client.ts +++ b/src/core/server/elasticsearch/client/cluster_client.ts @@ -22,7 +22,7 @@ import { Logger } from '../../logging'; import { GetAuthHeaders, isRealRequest, Headers } from '../../http'; import { ensureRawRequest, filterHeaders } from '../../http/router'; import { ScopeableRequest } from '../types'; -import { ElasticSearchClient } from './types'; +import { ElasticsearchClient } from './types'; import { configureClient } from './configure_client'; import { ElasticsearchClientConfig } from './client_config'; import { ScopedClusterClient, IScopedClusterClient } from './scoped_cluster_client'; @@ -38,9 +38,9 @@ const noop = () => undefined; **/ export interface IClusterClient { /** - * A {@link ElasticSearchClient | client} to be used to query the ES cluster on behalf of the Kibana internal user + * A {@link ElasticsearchClient | client} to be used to query the ES cluster on behalf of the Kibana internal user */ - readonly asInternalUser: ElasticSearchClient; + readonly asInternalUser: ElasticsearchClient; /** * Creates a {@link IScopedClusterClient | scoped cluster client} bound to given {@link ScopeableRequest | request} */ diff --git a/src/core/server/elasticsearch/client/index.ts b/src/core/server/elasticsearch/client/index.ts index 1a2f1f013d69f..18e84482024ca 100644 --- a/src/core/server/elasticsearch/client/index.ts +++ b/src/core/server/elasticsearch/client/index.ts @@ -17,7 +17,7 @@ * under the License. */ -export { ElasticSearchClient } from './types'; +export { ElasticsearchClient } from './types'; export { IScopedClusterClient, ScopedClusterClient } from './scoped_cluster_client'; export { ElasticsearchClientConfig } from './client_config'; export { IClusterClient, ICustomClusterClient, ClusterClient } from './cluster_client'; diff --git a/src/core/server/elasticsearch/client/mocks.ts b/src/core/server/elasticsearch/client/mocks.ts index 36cc27a5ba3ee..75644435a7f2a 100644 --- a/src/core/server/elasticsearch/client/mocks.ts +++ b/src/core/server/elasticsearch/client/mocks.ts @@ -19,7 +19,7 @@ import { Client, ApiResponse } from '@elastic/elasticsearch'; import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport'; -import { ElasticSearchClient } from './types'; +import { ElasticsearchClient } from './types'; import { ICustomClusterClient } from './cluster_client'; const createInternalClientMock = (): DeeplyMockedKeys => { @@ -63,7 +63,7 @@ const createInternalClientMock = (): DeeplyMockedKeys => { return (client as unknown) as DeeplyMockedKeys; }; -export type ElasticSearchClientMock = DeeplyMockedKeys; +export type ElasticSearchClientMock = DeeplyMockedKeys; const createClientMock = (): ElasticSearchClientMock => (createInternalClientMock() as unknown) as ElasticSearchClientMock; diff --git a/src/core/server/elasticsearch/client/scoped_cluster_client.ts b/src/core/server/elasticsearch/client/scoped_cluster_client.ts index 51a51db190c2d..1af7948a65e16 100644 --- a/src/core/server/elasticsearch/client/scoped_cluster_client.ts +++ b/src/core/server/elasticsearch/client/scoped_cluster_client.ts @@ -17,7 +17,7 @@ * under the License. */ -import { ElasticSearchClient } from './types'; +import { ElasticsearchClient } from './types'; /** * Serves the same purpose as the normal {@link ClusterClient | cluster client} but exposes @@ -29,21 +29,21 @@ import { ElasticSearchClient } from './types'; **/ export interface IScopedClusterClient { /** - * A {@link ElasticSearchClient | client} to be used to query the elasticsearch cluster + * A {@link ElasticsearchClient | client} to be used to query the elasticsearch cluster * on behalf of the internal Kibana user. */ - readonly asInternalUser: ElasticSearchClient; + readonly asInternalUser: ElasticsearchClient; /** - * A {@link ElasticSearchClient | client} to be used to query the elasticsearch cluster + * A {@link ElasticsearchClient | client} to be used to query the elasticsearch cluster * on behalf of the user that initiated the request to the Kibana server. */ - readonly asCurrentUser: ElasticSearchClient; + readonly asCurrentUser: ElasticsearchClient; } /** @internal **/ export class ScopedClusterClient implements IScopedClusterClient { constructor( - public readonly asInternalUser: ElasticSearchClient, - public readonly asCurrentUser: ElasticSearchClient + public readonly asInternalUser: ElasticsearchClient, + public readonly asCurrentUser: ElasticsearchClient ) {} } diff --git a/src/core/server/elasticsearch/client/types.ts b/src/core/server/elasticsearch/client/types.ts index 6e93c2dddaa22..934120c330e92 100644 --- a/src/core/server/elasticsearch/client/types.ts +++ b/src/core/server/elasticsearch/client/types.ts @@ -29,7 +29,7 @@ import type { * * @public */ -export type ElasticSearchClient = Omit< +export type ElasticsearchClient = Omit< Client, 'connectionPool' | 'transport' | 'serializer' | 'extend' | 'helpers' | 'child' | 'close' > & { diff --git a/src/core/server/elasticsearch/index.ts b/src/core/server/elasticsearch/index.ts index c5ee9f5e3d17b..8bb77b5dfdee0 100644 --- a/src/core/server/elasticsearch/index.ts +++ b/src/core/server/elasticsearch/index.ts @@ -34,6 +34,6 @@ export { IClusterClient, ICustomClusterClient, ElasticsearchClientConfig, - ElasticSearchClient, + ElasticsearchClient, IScopedClusterClient, } from './client'; From 022e4a28a86f631156616b614e469771bb8d97c3 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 7 Jul 2020 13:18:44 +0200 Subject: [PATCH 41/42] add test for encoded querystring --- .../client/configure_client.test.ts | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/core/server/elasticsearch/client/configure_client.test.ts b/src/core/server/elasticsearch/client/configure_client.test.ts index ba61e940d601b..32da142764a78 100644 --- a/src/core/server/elasticsearch/client/configure_client.test.ts +++ b/src/core/server/elasticsearch/client/configure_client.test.ts @@ -179,6 +179,42 @@ describe('configureClient', () => { `); }); + it('properly encode queries', () => { + const client = configureClient( + createFakeConfig({ + logQueries: true, + }), + { logger, scoped: false } + ); + + const response = createApiResponse({ + body: {}, + statusCode: 200, + params: { + method: 'GET', + path: '/foo', + querystring: { city: 'Münich' }, + }, + }); + + client.emit('response', null, response); + + expect(loggingSystemMock.collect(logger).debug).toMatchInlineSnapshot(` + Array [ + Array [ + "200 + GET /foo + city=M%C3%BCnich", + Object { + "tags": Array [ + "query", + ], + }, + ], + ] + `); + }); + it('logs queries even in case of errors if `logQueries` is true', () => { const client = configureClient( createFakeConfig({ From 5acfe964ec4a909acffb29618b066f8991ae6fd8 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 8 Jul 2020 11:12:38 +0200 Subject: [PATCH 42/42] adapt test file --- .../elasticsearch_service.test.ts | 50 ++++++++++--------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/src/core/server/elasticsearch/elasticsearch_service.test.ts b/src/core/server/elasticsearch/elasticsearch_service.test.ts index d5b5606fd8d61..b36af2a7e4671 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.test.ts @@ -28,6 +28,7 @@ import { CoreContext } from '../core_context'; import { configServiceMock } from '../config/config_service.mock'; import { loggingSystemMock } from '../logging/logging_system.mock'; import { httpServiceMock } from '../http/http_service.mock'; +import { auditTrailServiceMock } from '../audit_trail/audit_trail_service.mock'; import { ElasticsearchConfig } from './elasticsearch_config'; import { ElasticsearchService } from './elasticsearch_service'; import { elasticsearchServiceMock } from './elasticsearch_service.mock'; @@ -39,9 +40,12 @@ const delay = async (durationMs: number) => let elasticsearchService: ElasticsearchService; const configService = configServiceMock.create(); -const deps = { +const setupDeps = { http: httpServiceMock.createInternalSetupContract(), }; +const startDeps = { + auditTrail: auditTrailServiceMock.createStartContract(), +}; configService.atPath.mockReturnValue( new BehaviorSubject({ hosts: ['http://1.2.3.4'], @@ -59,7 +63,7 @@ let coreContext: CoreContext; const logger = loggingSystemMock.create(); let mockClusterClientInstance: ReturnType; -let mockLegacyClusterClientInstance: ReturnType; +let mockLegacyClusterClientInstance: ReturnType; beforeEach(() => { env = Env.createDefault(getEnvOptions()); @@ -70,7 +74,7 @@ beforeEach(() => { MockLegacyClusterClient.mockClear(); MockClusterClient.mockClear(); - mockLegacyClusterClientInstance = elasticsearchServiceMock.createCustomClusterClient(); + mockLegacyClusterClientInstance = elasticsearchServiceMock.createLegacyCustomClusterClient(); MockLegacyClusterClient.mockImplementation(() => mockLegacyClusterClientInstance); mockClusterClientInstance = elasticsearchClientMock.createCustomClusterClient(); MockClusterClient.mockImplementation(() => mockClusterClientInstance); @@ -80,7 +84,7 @@ afterEach(() => jest.clearAllMocks()); describe('#setup', () => { it('returns legacy Elasticsearch config as a part of the contract', async () => { - const setupContract = await elasticsearchService.setup(deps); + const setupContract = await elasticsearchService.setup(setupDeps); await expect(setupContract.legacy.config$.pipe(first()).toPromise()).resolves.toBeInstanceOf( ElasticsearchConfig @@ -88,7 +92,7 @@ describe('#setup', () => { }); it('returns legacy elasticsearch client as a part of the contract', async () => { - const setupContract = await elasticsearchService.setup(deps); + const setupContract = await elasticsearchService.setup(setupDeps); const client = setupContract.legacy.client; expect(mockLegacyClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(0); @@ -98,7 +102,7 @@ describe('#setup', () => { describe('#createLegacyClient', () => { it('allows to specify config properties', async () => { - const setupContract = await elasticsearchService.setup(deps); + const setupContract = await elasticsearchService.setup(setupDeps); // reset all mocks called during setup phase MockLegacyClusterClient.mockClear(); @@ -117,7 +121,7 @@ describe('#setup', () => { }); it('falls back to elasticsearch default config values if property not specified', async () => { - const setupContract = await elasticsearchService.setup(deps); + const setupContract = await elasticsearchService.setup(setupDeps); // reset all mocks called during setup phase MockLegacyClusterClient.mockClear(); @@ -148,7 +152,7 @@ describe('#setup', () => { `); }); it('falls back to elasticsearch config if custom config not passed', async () => { - const setupContract = await elasticsearchService.setup(deps); + const setupContract = await elasticsearchService.setup(setupDeps); // reset all mocks called during setup phase MockLegacyClusterClient.mockClear(); @@ -190,7 +194,7 @@ describe('#setup', () => { } as any) ); elasticsearchService = new ElasticsearchService(coreContext); - const setupContract = await elasticsearchService.setup(deps); + const setupContract = await elasticsearchService.setup(setupDeps); // reset all mocks called during setup phase MockLegacyClusterClient.mockClear(); @@ -225,7 +229,7 @@ describe('#setup', () => { it('esNodeVersionCompatibility$ only starts polling when subscribed to', async (done) => { mockLegacyClusterClientInstance.callAsInternalUser.mockRejectedValue(new Error()); - const setupContract = await elasticsearchService.setup(deps); + const setupContract = await elasticsearchService.setup(setupDeps); await delay(10); expect(mockLegacyClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(0); @@ -238,7 +242,7 @@ describe('#setup', () => { it('esNodeVersionCompatibility$ stops polling when unsubscribed from', async (done) => { mockLegacyClusterClientInstance.callAsInternalUser.mockRejectedValue(new Error()); - const setupContract = await elasticsearchService.setup(deps); + const setupContract = await elasticsearchService.setup(setupDeps); expect(mockLegacyClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(0); const sub = setupContract.esNodesCompatibility$.subscribe(async () => { @@ -252,14 +256,14 @@ describe('#setup', () => { describe('#start', () => { it('throws if called before `setup`', async () => { - expect(() => elasticsearchService.start()).rejects.toMatchInlineSnapshot( + expect(() => elasticsearchService.start(startDeps)).rejects.toMatchInlineSnapshot( `[Error: ElasticsearchService needs to be setup before calling start]` ); }); it('returns elasticsearch client as a part of the contract', async () => { - await elasticsearchService.setup(deps); - const startContract = await elasticsearchService.start(); + await elasticsearchService.setup(setupDeps); + const startContract = await elasticsearchService.start(startDeps); const client = startContract.client; expect(client.asInternalUser).toBe(mockClusterClientInstance.asInternalUser); @@ -267,8 +271,8 @@ describe('#start', () => { describe('#createClient', () => { it('allows to specify config properties', async () => { - await elasticsearchService.setup(deps); - const startContract = await elasticsearchService.start(); + await elasticsearchService.setup(setupDeps); + const startContract = await elasticsearchService.start(startDeps); // reset all mocks called during setup phase MockClusterClient.mockClear(); @@ -286,8 +290,8 @@ describe('#start', () => { ); }); it('creates a new client on each call', async () => { - await elasticsearchService.setup(deps); - const startContract = await elasticsearchService.start(); + await elasticsearchService.setup(setupDeps); + const startContract = await elasticsearchService.start(startDeps); // reset all mocks called during setup phase MockClusterClient.mockClear(); @@ -301,8 +305,8 @@ describe('#start', () => { }); it('falls back to elasticsearch default config values if property not specified', async () => { - await elasticsearchService.setup(deps); - const startContract = await elasticsearchService.start(); + await elasticsearchService.setup(setupDeps); + const startContract = await elasticsearchService.start(startDeps); // reset all mocks called during setup phase MockClusterClient.mockClear(); @@ -338,8 +342,8 @@ describe('#start', () => { describe('#stop', () => { it('stops both legacy and new clients', async () => { - await elasticsearchService.setup(deps); - await elasticsearchService.start(); + await elasticsearchService.setup(setupDeps); + await elasticsearchService.start(startDeps); await elasticsearchService.stop(); expect(mockLegacyClusterClientInstance.close).toHaveBeenCalledTimes(1); @@ -351,7 +355,7 @@ describe('#stop', () => { mockLegacyClusterClientInstance.callAsInternalUser.mockRejectedValue(new Error()); - const setupContract = await elasticsearchService.setup(deps); + const setupContract = await elasticsearchService.setup(setupDeps); setupContract.esNodesCompatibility$.subscribe(async () => { expect(mockLegacyClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(1);