[Elasticsearch] remove legacy es client (#107619) (#109144)

* remove legacy es client

* update docs

* uninstall elasticsearch package

* fix global_search tests

* ad-hoc fix to address bazel failure. authored by Tiago

* update docs

* remove elasticsearch import. errors are muted with @ts-ignore

* Update WORKSPACE.bazel

Co-authored-by: Tiago Costa <tiagoffcc@hotmail.com>

* update docs

* fix problem when dev mock already mocked client

Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
Co-authored-by: Tiago Costa <tiagoffcc@hotmail.com>
# Conflicts:
#	src/core/server/elasticsearch/legacy/scoped_cluster_client.test.ts
This commit is contained in:
Mikhail Shustov 2021-08-18 22:41:25 +03:00 committed by GitHub
parent 0101c8d9b6
commit 9f78d17e8f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
91 changed files with 43 additions and 4619 deletions

View file

@ -1,15 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [AssistanceAPIResponse](./kibana-plugin-core-server.assistanceapiresponse.md) &gt; [indices](./kibana-plugin-core-server.assistanceapiresponse.indices.md)
## AssistanceAPIResponse.indices property
<b>Signature:</b>
```typescript
indices: {
[indexName: string]: {
action_required: MIGRATION_ASSISTANCE_INDEX_ACTION;
};
};
```

View file

@ -1,23 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [AssistanceAPIResponse](./kibana-plugin-core-server.assistanceapiresponse.md)
## AssistanceAPIResponse interface
> Warning: This API is now obsolete.
>
> 7.16
>
<b>Signature:</b>
```typescript
export interface AssistanceAPIResponse
```
## Properties
| Property | Type | Description |
| --- | --- | --- |
| [indices](./kibana-plugin-core-server.assistanceapiresponse.indices.md) | <code>{</code><br/><code> [indexName: string]: {</code><br/><code> action_required: MIGRATION_ASSISTANCE_INDEX_ACTION;</code><br/><code> };</code><br/><code> }</code> | |

View file

@ -1,24 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [AssistantAPIClientParams](./kibana-plugin-core-server.assistantapiclientparams.md)
## AssistantAPIClientParams interface
> Warning: This API is now obsolete.
>
> 7.16
>
<b>Signature:</b>
```typescript
export interface AssistantAPIClientParams extends GenericParams
```
## Properties
| Property | Type | Description |
| --- | --- | --- |
| [method](./kibana-plugin-core-server.assistantapiclientparams.method.md) | <code>'GET'</code> | |
| [path](./kibana-plugin-core-server.assistantapiclientparams.path.md) | <code>'/_migration/assistance'</code> | |

View file

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [AssistantAPIClientParams](./kibana-plugin-core-server.assistantapiclientparams.md) &gt; [method](./kibana-plugin-core-server.assistantapiclientparams.method.md)
## AssistantAPIClientParams.method property
<b>Signature:</b>
```typescript
method: 'GET';
```

View file

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [AssistantAPIClientParams](./kibana-plugin-core-server.assistantapiclientparams.md) &gt; [path](./kibana-plugin-core-server.assistantapiclientparams.path.md)
## AssistantAPIClientParams.path property
<b>Signature:</b>
```typescript
path: '/_migration/assistance';
```

View file

@ -1,24 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [DeprecationAPIClientParams](./kibana-plugin-core-server.deprecationapiclientparams.md)
## DeprecationAPIClientParams interface
> Warning: This API is now obsolete.
>
> 7.16
>
<b>Signature:</b>
```typescript
export interface DeprecationAPIClientParams extends GenericParams
```
## Properties
| Property | Type | Description |
| --- | --- | --- |
| [method](./kibana-plugin-core-server.deprecationapiclientparams.method.md) | <code>'GET'</code> | |
| [path](./kibana-plugin-core-server.deprecationapiclientparams.path.md) | <code>'/_migration/deprecations'</code> | |

View file

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [DeprecationAPIClientParams](./kibana-plugin-core-server.deprecationapiclientparams.md) &gt; [method](./kibana-plugin-core-server.deprecationapiclientparams.method.md)
## DeprecationAPIClientParams.method property
<b>Signature:</b>
```typescript
method: 'GET';
```

View file

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [DeprecationAPIClientParams](./kibana-plugin-core-server.deprecationapiclientparams.md) &gt; [path](./kibana-plugin-core-server.deprecationapiclientparams.path.md)
## DeprecationAPIClientParams.path property
<b>Signature:</b>
```typescript
path: '/_migration/deprecations';
```

View file

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [DeprecationAPIResponse](./kibana-plugin-core-server.deprecationapiresponse.md) &gt; [cluster\_settings](./kibana-plugin-core-server.deprecationapiresponse.cluster_settings.md)
## DeprecationAPIResponse.cluster\_settings property
<b>Signature:</b>
```typescript
cluster_settings: DeprecationInfo[];
```

View file

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [DeprecationAPIResponse](./kibana-plugin-core-server.deprecationapiresponse.md) &gt; [index\_settings](./kibana-plugin-core-server.deprecationapiresponse.index_settings.md)
## DeprecationAPIResponse.index\_settings property
<b>Signature:</b>
```typescript
index_settings: IndexSettingsDeprecationInfo;
```

View file

@ -1,26 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [DeprecationAPIResponse](./kibana-plugin-core-server.deprecationapiresponse.md)
## DeprecationAPIResponse interface
> Warning: This API is now obsolete.
>
> 7.16
>
<b>Signature:</b>
```typescript
export interface DeprecationAPIResponse
```
## Properties
| Property | Type | Description |
| --- | --- | --- |
| [cluster\_settings](./kibana-plugin-core-server.deprecationapiresponse.cluster_settings.md) | <code>DeprecationInfo[]</code> | |
| [index\_settings](./kibana-plugin-core-server.deprecationapiresponse.index_settings.md) | <code>IndexSettingsDeprecationInfo</code> | |
| [ml\_settings](./kibana-plugin-core-server.deprecationapiresponse.ml_settings.md) | <code>DeprecationInfo[]</code> | |
| [node\_settings](./kibana-plugin-core-server.deprecationapiresponse.node_settings.md) | <code>DeprecationInfo[]</code> | |

View file

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [DeprecationAPIResponse](./kibana-plugin-core-server.deprecationapiresponse.md) &gt; [ml\_settings](./kibana-plugin-core-server.deprecationapiresponse.ml_settings.md)
## DeprecationAPIResponse.ml\_settings property
<b>Signature:</b>
```typescript
ml_settings: DeprecationInfo[];
```

View file

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [DeprecationAPIResponse](./kibana-plugin-core-server.deprecationapiresponse.md) &gt; [node\_settings](./kibana-plugin-core-server.deprecationapiresponse.node_settings.md)
## DeprecationAPIResponse.node\_settings property
<b>Signature:</b>
```typescript
node_settings: DeprecationInfo[];
```

View file

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [DeprecationInfo](./kibana-plugin-core-server.deprecationinfo.md) &gt; [details](./kibana-plugin-core-server.deprecationinfo.details.md)
## DeprecationInfo.details property
<b>Signature:</b>
```typescript
details?: string;
```

View file

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [DeprecationInfo](./kibana-plugin-core-server.deprecationinfo.md) &gt; [level](./kibana-plugin-core-server.deprecationinfo.level.md)
## DeprecationInfo.level property
<b>Signature:</b>
```typescript
level: MIGRATION_DEPRECATION_LEVEL;
```

View file

@ -1,26 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [DeprecationInfo](./kibana-plugin-core-server.deprecationinfo.md)
## DeprecationInfo interface
> Warning: This API is now obsolete.
>
> 7.16
>
<b>Signature:</b>
```typescript
export interface DeprecationInfo
```
## Properties
| Property | Type | Description |
| --- | --- | --- |
| [details](./kibana-plugin-core-server.deprecationinfo.details.md) | <code>string</code> | |
| [level](./kibana-plugin-core-server.deprecationinfo.level.md) | <code>MIGRATION_DEPRECATION_LEVEL</code> | |
| [message](./kibana-plugin-core-server.deprecationinfo.message.md) | <code>string</code> | |
| [url](./kibana-plugin-core-server.deprecationinfo.url.md) | <code>string</code> | |

View file

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [DeprecationInfo](./kibana-plugin-core-server.deprecationinfo.md) &gt; [message](./kibana-plugin-core-server.deprecationinfo.message.md)
## DeprecationInfo.message property
<b>Signature:</b>
```typescript
message: string;
```

View file

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [DeprecationInfo](./kibana-plugin-core-server.deprecationinfo.md) &gt; [url](./kibana-plugin-core-server.deprecationinfo.url.md)
## DeprecationInfo.url property
<b>Signature:</b>
```typescript
url: string;
```

View file

@ -14,7 +14,5 @@
```typescript
legacy: {
readonly config$: Observable<ElasticsearchConfig>;
readonly createClient: (type: string, clientConfig?: Partial<LegacyElasticsearchClientConfig>) => ILegacyCustomClusterClient;
readonly client: ILegacyClusterClient;
};
```

View file

@ -15,5 +15,5 @@ export interface ElasticsearchServiceSetup
| Property | Type | Description |
| --- | --- | --- |
| [legacy](./kibana-plugin-core-server.elasticsearchservicesetup.legacy.md) | <code>{</code><br/><code> readonly config$: Observable&lt;ElasticsearchConfig&gt;;</code><br/><code> readonly createClient: (type: string, clientConfig?: Partial&lt;LegacyElasticsearchClientConfig&gt;) =&gt; ILegacyCustomClusterClient;</code><br/><code> readonly client: ILegacyClusterClient;</code><br/><code> }</code> | |
| [legacy](./kibana-plugin-core-server.elasticsearchservicesetup.legacy.md) | <code>{</code><br/><code> readonly config$: Observable&lt;ElasticsearchConfig&gt;;</code><br/><code> }</code> | |

View file

@ -14,7 +14,5 @@
```typescript
legacy: {
readonly config$: Observable<ElasticsearchConfig>;
readonly createClient: (type: string, clientConfig?: Partial<LegacyElasticsearchClientConfig>) => ILegacyCustomClusterClient;
readonly client: ILegacyClusterClient;
};
```

View file

@ -17,5 +17,5 @@ export interface ElasticsearchServiceStart
| --- | --- | --- |
| [client](./kibana-plugin-core-server.elasticsearchservicestart.client.md) | <code>IClusterClient</code> | A pre-configured [Elasticsearch client](./kibana-plugin-core-server.iclusterclient.md) |
| [createClient](./kibana-plugin-core-server.elasticsearchservicestart.createclient.md) | <code>(type: string, clientConfig?: Partial&lt;ElasticsearchClientConfig&gt;) =&gt; ICustomClusterClient</code> | Create application specific Elasticsearch cluster API client with customized config. See [IClusterClient](./kibana-plugin-core-server.iclusterclient.md)<!-- -->. |
| [legacy](./kibana-plugin-core-server.elasticsearchservicestart.legacy.md) | <code>{</code><br/><code> readonly config$: Observable&lt;ElasticsearchConfig&gt;;</code><br/><code> readonly createClient: (type: string, clientConfig?: Partial&lt;LegacyElasticsearchClientConfig&gt;) =&gt; ILegacyCustomClusterClient;</code><br/><code> readonly client: ILegacyClusterClient;</code><br/><code> }</code> | |
| [legacy](./kibana-plugin-core-server.elasticsearchservicestart.legacy.md) | <code>{</code><br/><code> readonly config$: Observable&lt;ElasticsearchConfig&gt;;</code><br/><code> }</code> | |

View file

@ -1,20 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [ILegacyClusterClient](./kibana-plugin-core-server.ilegacyclusterclient.md)
## ILegacyClusterClient type
> Warning: This API is now obsolete.
>
> Use [IClusterClient](./kibana-plugin-core-server.iclusterclient.md)<!-- -->. 7.16
>
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(...)`<!-- -->).
See [LegacyClusterClient](./kibana-plugin-core-server.legacyclusterclient.md)<!-- -->.
<b>Signature:</b>
```typescript
export declare type ILegacyClusterClient = Pick<LegacyClusterClient, 'callAsInternalUser' | 'asScoped'>;
```

View file

@ -1,20 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [ILegacyCustomClusterClient](./kibana-plugin-core-server.ilegacycustomclusterclient.md)
## ILegacyCustomClusterClient type
> Warning: This API is now obsolete.
>
> Use [ICustomClusterClient](./kibana-plugin-core-server.icustomclusterclient.md)<!-- -->. 7.16
>
Represents an Elasticsearch cluster API client created by a plugin. 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(...)`<!-- -->).
See [LegacyClusterClient](./kibana-plugin-core-server.legacyclusterclient.md)<!-- -->.
<b>Signature:</b>
```typescript
export declare type ILegacyCustomClusterClient = Pick<LegacyClusterClient, 'callAsInternalUser' | 'close' | 'asScoped'>;
```

View file

@ -1,20 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [ILegacyScopedClusterClient](./kibana-plugin-core-server.ilegacyscopedclusterclient.md)
## ILegacyScopedClusterClient type
> Warning: This API is now obsolete.
>
> Use [IScopedClusterClient](./kibana-plugin-core-server.iscopedclusterclient.md)<!-- -->. 7.16
>
Serves the same purpose as "normal" `ClusterClient` but exposes additional `callAsCurrentUser` method that doesn't use credentials of the Kibana internal user (as `callAsInternalUser` does) to request Elasticsearch API, but rather passes HTTP headers extracted from the current user request to the API.
See [LegacyScopedClusterClient](./kibana-plugin-core-server.legacyscopedclusterclient.md)<!-- -->.
<b>Signature:</b>
```typescript
export declare type ILegacyScopedClusterClient = Pick<LegacyScopedClusterClient, 'callAsCurrentUser' | 'callAsInternalUser'>;
```

View file

@ -1,16 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [IndexSettingsDeprecationInfo](./kibana-plugin-core-server.indexsettingsdeprecationinfo.md)
## IndexSettingsDeprecationInfo interface
> Warning: This API is now obsolete.
>
> 7.16
>
<b>Signature:</b>
```typescript
export interface IndexSettingsDeprecationInfo
```

View file

@ -1,16 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyAPICaller](./kibana-plugin-core-server.legacyapicaller.md)
## LegacyAPICaller interface
> Warning: This API is now obsolete.
>
> 7.16
>
<b>Signature:</b>
```typescript
export interface LegacyAPICaller
```

View file

@ -1,26 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyCallAPIOptions](./kibana-plugin-core-server.legacycallapioptions.md)
## LegacyCallAPIOptions interface
> Warning: This API is now obsolete.
>
> 7.16
>
The set of options that defines how API call should be made and result be processed.
<b>Signature:</b>
```typescript
export interface LegacyCallAPIOptions
```
## Properties
| Property | Type | Description |
| --- | --- | --- |
| [signal](./kibana-plugin-core-server.legacycallapioptions.signal.md) | <code>AbortSignal</code> | A signal object that allows you to abort the request via an AbortController object. |
| [wrap401Errors](./kibana-plugin-core-server.legacycallapioptions.wrap401errors.md) | <code>boolean</code> | Indicates whether <code>401 Unauthorized</code> errors returned from the Elasticsearch API should be wrapped into <code>Boom</code> error instances with properly set <code>WWW-Authenticate</code> header that could have been returned by the API itself. If API didn't specify that then <code>Basic realm=&quot;Authorization Required&quot;</code> is used as <code>WWW-Authenticate</code>. |

View file

@ -1,13 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyCallAPIOptions](./kibana-plugin-core-server.legacycallapioptions.md) &gt; [signal](./kibana-plugin-core-server.legacycallapioptions.signal.md)
## LegacyCallAPIOptions.signal property
A signal object that allows you to abort the request via an AbortController object.
<b>Signature:</b>
```typescript
signal?: AbortSignal;
```

View file

@ -1,13 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyCallAPIOptions](./kibana-plugin-core-server.legacycallapioptions.md) &gt; [wrap401Errors](./kibana-plugin-core-server.legacycallapioptions.wrap401errors.md)
## LegacyCallAPIOptions.wrap401Errors property
Indicates whether `401 Unauthorized` errors returned from the Elasticsearch API should be wrapped into `Boom` error instances with properly set `WWW-Authenticate` header that could have been returned by the API itself. If API didn't specify that then `Basic realm="Authorization Required"` is used as `WWW-Authenticate`<!-- -->.
<b>Signature:</b>
```typescript
wrap401Errors?: boolean;
```

View file

@ -1,23 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyClusterClient](./kibana-plugin-core-server.legacyclusterclient.md) &gt; [(constructor)](./kibana-plugin-core-server.legacyclusterclient._constructor_.md)
## LegacyClusterClient.(constructor)
Constructs a new instance of the `LegacyClusterClient` class
<b>Signature:</b>
```typescript
constructor(config: LegacyElasticsearchClientConfig, log: Logger, type: string, getAuthHeaders?: GetAuthHeaders);
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| config | <code>LegacyElasticsearchClientConfig</code> | |
| log | <code>Logger</code> | |
| type | <code>string</code> | |
| getAuthHeaders | <code>GetAuthHeaders</code> | |

View file

@ -1,24 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyClusterClient](./kibana-plugin-core-server.legacyclusterclient.md) &gt; [asScoped](./kibana-plugin-core-server.legacyclusterclient.asscoped.md)
## LegacyClusterClient.asScoped() method
Creates an instance of [ILegacyScopedClusterClient](./kibana-plugin-core-server.ilegacyscopedclusterclient.md) based on the configuration the current cluster client that exposes additional `callAsCurrentUser` method scoped to the provided req. Consumers shouldn't worry about closing scoped client instances, these will be automatically closed as soon as the original cluster client isn't needed anymore and closed.
<b>Signature:</b>
```typescript
asScoped(request?: ScopeableRequest): ILegacyScopedClusterClient;
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| request | <code>ScopeableRequest</code> | Request the <code>IScopedClusterClient</code> instance will be scoped to. Supports request optionality, Legacy.Request &amp; FakeRequest for BWC with LegacyPlatform |
<b>Returns:</b>
`ILegacyScopedClusterClient`

View file

@ -1,18 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyClusterClient](./kibana-plugin-core-server.legacyclusterclient.md) &gt; [callAsInternalUser](./kibana-plugin-core-server.legacyclusterclient.callasinternaluser.md)
## LegacyClusterClient.callAsInternalUser property
> Warning: This API is now obsolete.
>
> Use [IClusterClient.asInternalUser](./kibana-plugin-core-server.iclusterclient.asinternaluser.md)<!-- -->.
>
Calls specified endpoint with provided clientParams on behalf of the Kibana internal user. See [LegacyAPICaller](./kibana-plugin-core-server.legacyapicaller.md)<!-- -->.
<b>Signature:</b>
```typescript
callAsInternalUser: LegacyAPICaller;
```

View file

@ -1,17 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyClusterClient](./kibana-plugin-core-server.legacyclusterclient.md) &gt; [close](./kibana-plugin-core-server.legacyclusterclient.close.md)
## LegacyClusterClient.close() method
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.
<b>Signature:</b>
```typescript
close(): void;
```
<b>Returns:</b>
`void`

View file

@ -1,38 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyClusterClient](./kibana-plugin-core-server.legacyclusterclient.md)
## LegacyClusterClient class
> Warning: This API is now obsolete.
>
> Use [IClusterClient](./kibana-plugin-core-server.iclusterclient.md)<!-- -->. 7.16
>
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(...)`<!-- -->).
<b>Signature:</b>
```typescript
export declare class LegacyClusterClient implements ILegacyClusterClient
```
## Constructors
| Constructor | Modifiers | Description |
| --- | --- | --- |
| [(constructor)(config, log, type, getAuthHeaders)](./kibana-plugin-core-server.legacyclusterclient._constructor_.md) | | Constructs a new instance of the <code>LegacyClusterClient</code> class |
## Properties
| Property | Modifiers | Type | Description |
| --- | --- | --- | --- |
| [callAsInternalUser](./kibana-plugin-core-server.legacyclusterclient.callasinternaluser.md) | | <code>LegacyAPICaller</code> | Calls specified endpoint with provided clientParams on behalf of the Kibana internal user. See [LegacyAPICaller](./kibana-plugin-core-server.legacyapicaller.md)<!-- -->. |
## Methods
| Method | Modifiers | Description |
| --- | --- | --- |
| [asScoped(request)](./kibana-plugin-core-server.legacyclusterclient.asscoped.md) | | Creates an instance of [ILegacyScopedClusterClient](./kibana-plugin-core-server.ilegacyscopedclusterclient.md) based on the configuration the current cluster client that exposes additional <code>callAsCurrentUser</code> method scoped to the provided req. Consumers shouldn't worry about closing scoped client instances, these will be automatically closed as soon as the original cluster client isn't needed anymore and closed. |
| [close()](./kibana-plugin-core-server.legacyclusterclient.close.md) | | 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. |

View file

@ -1,20 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyElasticsearchClientConfig](./kibana-plugin-core-server.legacyelasticsearchclientconfig.md)
## LegacyElasticsearchClientConfig type
> Warning: This API is now obsolete.
>
>
<b>Signature:</b>
```typescript
export declare type LegacyElasticsearchClientConfig = Pick<ConfigOptions, 'keepAlive' | 'log' | 'plugins'> & Pick<ElasticsearchConfig, 'apiVersion' | 'customHeaders' | 'requestHeadersWhitelist' | 'sniffOnStart' | 'sniffOnConnectionFault' | 'hosts' | 'username' | 'password' | 'serviceAccountToken'> & {
pingTimeout?: ElasticsearchConfig['pingTimeout'] | ConfigOptions['pingTimeout'];
requestTimeout?: ElasticsearchConfig['requestTimeout'] | ConfigOptions['requestTimeout'];
sniffInterval?: ElasticsearchConfig['sniffInterval'] | ConfigOptions['sniffInterval'];
ssl?: Partial<ElasticsearchConfig['ssl']>;
};
```

View file

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyElasticsearchError](./kibana-plugin-core-server.legacyelasticsearcherror.md) &gt; [\[code\]](./kibana-plugin-core-server.legacyelasticsearcherror._code_.md)
## LegacyElasticsearchError.\[code\] property
<b>Signature:</b>
```typescript
[code]?: string;
```

View file

@ -1,20 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyElasticsearchError](./kibana-plugin-core-server.legacyelasticsearcherror.md)
## LegacyElasticsearchError interface
@<!-- -->deprecated. The new elasticsearch client doesn't wrap errors anymore. 7.16
<b>Signature:</b>
```typescript
export interface LegacyElasticsearchError extends Boom.Boom
```
## Properties
| Property | Type | Description |
| --- | --- | --- |
| [\[code\]](./kibana-plugin-core-server.legacyelasticsearcherror._code_.md) | <code>string</code> | |

View file

@ -1,23 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyElasticsearchErrorHelpers](./kibana-plugin-core-server.legacyelasticsearcherrorhelpers.md) &gt; [decorateNotAuthorizedError](./kibana-plugin-core-server.legacyelasticsearcherrorhelpers.decoratenotauthorizederror.md)
## LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError() method
<b>Signature:</b>
```typescript
static decorateNotAuthorizedError(error: Error, reason?: string): LegacyElasticsearchError;
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| error | <code>Error</code> | |
| reason | <code>string</code> | |
<b>Returns:</b>
`LegacyElasticsearchError`

View file

@ -1,22 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyElasticsearchErrorHelpers](./kibana-plugin-core-server.legacyelasticsearcherrorhelpers.md) &gt; [isNotAuthorizedError](./kibana-plugin-core-server.legacyelasticsearcherrorhelpers.isnotauthorizederror.md)
## LegacyElasticsearchErrorHelpers.isNotAuthorizedError() method
<b>Signature:</b>
```typescript
static isNotAuthorizedError(error: any): error is LegacyElasticsearchError;
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| error | <code>any</code> | |
<b>Returns:</b>
`error is LegacyElasticsearchError`

View file

@ -1,35 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyElasticsearchErrorHelpers](./kibana-plugin-core-server.legacyelasticsearcherrorhelpers.md)
## LegacyElasticsearchErrorHelpers class
Helpers for working with errors returned from the Elasticsearch service.Since the internal data of errors are subject to change, consumers of the Elasticsearch service should always use these helpers to classify errors instead of checking error internals such as `body.error.header[WWW-Authenticate]`
<b>Signature:</b>
```typescript
export declare class LegacyElasticsearchErrorHelpers
```
## Example
Handle errors
```js
try {
await client.asScoped(request).callAsCurrentUser(...);
} catch (err) {
if (ElasticsearchErrorHelpers.isNotAuthorizedError(err)) {
const authHeader = err.output.headers['WWW-Authenticate'];
}
```
## Methods
| Method | Modifiers | Description |
| --- | --- | --- |
| [decorateNotAuthorizedError(error, reason)](./kibana-plugin-core-server.legacyelasticsearcherrorhelpers.decoratenotauthorizederror.md) | <code>static</code> | |
| [isNotAuthorizedError(error)](./kibana-plugin-core-server.legacyelasticsearcherrorhelpers.isnotauthorizederror.md) | <code>static</code> | |

View file

@ -1,22 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyScopedClusterClient](./kibana-plugin-core-server.legacyscopedclusterclient.md) &gt; [(constructor)](./kibana-plugin-core-server.legacyscopedclusterclient._constructor_.md)
## LegacyScopedClusterClient.(constructor)
Constructs a new instance of the `LegacyScopedClusterClient` class
<b>Signature:</b>
```typescript
constructor(internalAPICaller: LegacyAPICaller, scopedAPICaller: LegacyAPICaller, headers?: Headers | undefined);
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| internalAPICaller | <code>LegacyAPICaller</code> | |
| scopedAPICaller | <code>LegacyAPICaller</code> | |
| headers | <code>Headers &#124; undefined</code> | |

View file

@ -1,31 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyScopedClusterClient](./kibana-plugin-core-server.legacyscopedclusterclient.md) &gt; [callAsCurrentUser](./kibana-plugin-core-server.legacyscopedclusterclient.callascurrentuser.md)
## LegacyScopedClusterClient.callAsCurrentUser() method
> Warning: This API is now obsolete.
>
> Use [IScopedClusterClient.asCurrentUser](./kibana-plugin-core-server.iscopedclusterclient.ascurrentuser.md)<!-- -->. 7.16
>
Calls specified `endpoint` with provided `clientParams` on behalf of the user initiated request to the Kibana server (via HTTP request headers). See [LegacyAPICaller](./kibana-plugin-core-server.legacyapicaller.md)<!-- -->.
<b>Signature:</b>
```typescript
callAsCurrentUser(endpoint: string, clientParams?: Record<string, any>, options?: LegacyCallAPIOptions): Promise<any>;
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| endpoint | <code>string</code> | String descriptor of the endpoint e.g. <code>cluster.getSettings</code> or <code>ping</code>. |
| clientParams | <code>Record&lt;string, any&gt;</code> | A dictionary of parameters that will be passed directly to the Elasticsearch JS client. |
| options | <code>LegacyCallAPIOptions</code> | Options that affect the way we call the API and process the result. |
<b>Returns:</b>
`Promise<any>`

View file

@ -1,31 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyScopedClusterClient](./kibana-plugin-core-server.legacyscopedclusterclient.md) &gt; [callAsInternalUser](./kibana-plugin-core-server.legacyscopedclusterclient.callasinternaluser.md)
## LegacyScopedClusterClient.callAsInternalUser() method
> Warning: This API is now obsolete.
>
> Use [IScopedClusterClient.asInternalUser](./kibana-plugin-core-server.iscopedclusterclient.asinternaluser.md)<!-- -->. 7.16
>
Calls specified `endpoint` with provided `clientParams` on behalf of the Kibana internal user. See [LegacyAPICaller](./kibana-plugin-core-server.legacyapicaller.md)<!-- -->.
<b>Signature:</b>
```typescript
callAsInternalUser(endpoint: string, clientParams?: Record<string, any>, options?: LegacyCallAPIOptions): Promise<any>;
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| endpoint | <code>string</code> | String descriptor of the endpoint e.g. <code>cluster.getSettings</code> or <code>ping</code>. |
| clientParams | <code>Record&lt;string, any&gt;</code> | A dictionary of parameters that will be passed directly to the Elasticsearch JS client. |
| options | <code>LegacyCallAPIOptions</code> | Options that affect the way we call the API and process the result. |
<b>Returns:</b>
`Promise<any>`

View file

@ -1,32 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [LegacyScopedClusterClient](./kibana-plugin-core-server.legacyscopedclusterclient.md)
## LegacyScopedClusterClient class
> Warning: This API is now obsolete.
>
> Use [scoped cluster client](./kibana-plugin-core-server.iscopedclusterclient.md)<!-- -->. 7.16
>
Serves the same purpose as the normal [cluster client](./kibana-plugin-core-server.iclusterclient.md) 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.
<b>Signature:</b>
```typescript
export declare class LegacyScopedClusterClient implements ILegacyScopedClusterClient
```
## Constructors
| Constructor | Modifiers | Description |
| --- | --- | --- |
| [(constructor)(internalAPICaller, scopedAPICaller, headers)](./kibana-plugin-core-server.legacyscopedclusterclient._constructor_.md) | | Constructs a new instance of the <code>LegacyScopedClusterClient</code> class |
## Methods
| Method | Modifiers | Description |
| --- | --- | --- |
| [callAsCurrentUser(endpoint, clientParams, options)](./kibana-plugin-core-server.legacyscopedclusterclient.callascurrentuser.md) | | Calls specified <code>endpoint</code> with provided <code>clientParams</code> on behalf of the user initiated request to the Kibana server (via HTTP request headers). See [LegacyAPICaller](./kibana-plugin-core-server.legacyapicaller.md)<!-- -->. |
| [callAsInternalUser(endpoint, clientParams, options)](./kibana-plugin-core-server.legacyscopedclusterclient.callasinternaluser.md) | | Calls specified <code>endpoint</code> with provided <code>clientParams</code> on behalf of the Kibana internal user. See [LegacyAPICaller](./kibana-plugin-core-server.legacyapicaller.md)<!-- -->. |

View file

@ -20,9 +20,6 @@ The plugin integrates with the core system via lifecycle events: `setup`<!-- -->
| [CspConfig](./kibana-plugin-core-server.cspconfig.md) | CSP configuration for use in Kibana. |
| [ElasticsearchConfig](./kibana-plugin-core-server.elasticsearchconfig.md) | Wrapper of config schema. |
| [KibanaRequest](./kibana-plugin-core-server.kibanarequest.md) | Kibana specific abstraction for an incoming request. |
| [LegacyClusterClient](./kibana-plugin-core-server.legacyclusterclient.md) | 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 <code>asScoped(...)</code>). |
| [LegacyElasticsearchErrorHelpers](./kibana-plugin-core-server.legacyelasticsearcherrorhelpers.md) | Helpers for working with errors returned from the Elasticsearch service.Since the internal data of errors are subject to change, consumers of the Elasticsearch service should always use these helpers to classify errors instead of checking error internals such as <code>body.error.header[WWW-Authenticate]</code> |
| [LegacyScopedClusterClient](./kibana-plugin-core-server.legacyscopedclusterclient.md) | Serves the same purpose as the normal [cluster client](./kibana-plugin-core-server.iclusterclient.md) but exposes an additional <code>asCurrentUser</code> method that doesn't use credentials of the Kibana internal user (as <code>asInternalUser</code> does) to request Elasticsearch API, but rather passes HTTP headers extracted from the current user request to the API instead. |
| [RouteValidationError](./kibana-plugin-core-server.routevalidationerror.md) | Error to return when the validation is not successful. |
| [SavedObjectsClient](./kibana-plugin-core-server.savedobjectsclient.md) | |
| [SavedObjectsErrorHelpers](./kibana-plugin-core-server.savedobjectserrorhelpers.md) | |
@ -48,8 +45,6 @@ The plugin integrates with the core system via lifecycle events: `setup`<!-- -->
| Interface | Description |
| --- | --- |
| [AppCategory](./kibana-plugin-core-server.appcategory.md) | A category definition for nav links to know where to sort them in the left hand nav |
| [AssistanceAPIResponse](./kibana-plugin-core-server.assistanceapiresponse.md) | |
| [AssistantAPIClientParams](./kibana-plugin-core-server.assistantapiclientparams.md) | |
| [AsyncPlugin](./kibana-plugin-core-server.asyncplugin.md) | A plugin with asynchronous lifecycle methods. |
| [Authenticated](./kibana-plugin-core-server.authenticated.md) | |
| [AuthNotHandled](./kibana-plugin-core-server.authnothandled.md) | |
@ -68,9 +63,6 @@ The plugin integrates with the core system via lifecycle events: `setup`<!-- -->
| [CountResponse](./kibana-plugin-core-server.countresponse.md) | |
| [CustomHttpResponseOptions](./kibana-plugin-core-server.customhttpresponseoptions.md) | HTTP response parameters for a response with adjustable status code. |
| [DeleteDocumentResponse](./kibana-plugin-core-server.deletedocumentresponse.md) | |
| [DeprecationAPIClientParams](./kibana-plugin-core-server.deprecationapiclientparams.md) | |
| [DeprecationAPIResponse](./kibana-plugin-core-server.deprecationapiresponse.md) | |
| [DeprecationInfo](./kibana-plugin-core-server.deprecationinfo.md) | |
| [DeprecationsClient](./kibana-plugin-core-server.deprecationsclient.md) | Server-side client that provides access to fetch all Kibana deprecations |
| [DeprecationsDetails](./kibana-plugin-core-server.deprecationsdetails.md) | |
| [DeprecationSettings](./kibana-plugin-core-server.deprecationsettings.md) | UiSettings deprecation field options. |
@ -105,7 +97,6 @@ The plugin integrates with the core system via lifecycle events: `setup`<!-- -->
| [IExternalUrlPolicy](./kibana-plugin-core-server.iexternalurlpolicy.md) | A policy describing whether access to an external destination is allowed. |
| [IKibanaResponse](./kibana-plugin-core-server.ikibanaresponse.md) | A response data object, expected to returned as a result of [RequestHandler](./kibana-plugin-core-server.requesthandler.md) execution |
| [IKibanaSocket](./kibana-plugin-core-server.ikibanasocket.md) | A tiny abstraction for TCP socket. |
| [IndexSettingsDeprecationInfo](./kibana-plugin-core-server.indexsettingsdeprecationinfo.md) | |
| [IRenderOptions](./kibana-plugin-core-server.irenderoptions.md) | |
| [IRouter](./kibana-plugin-core-server.irouter.md) | Registers route handlers for specified resource path and method. See [RouteConfig](./kibana-plugin-core-server.routeconfig.md) and [RequestHandler](./kibana-plugin-core-server.requesthandler.md) for more information about arguments to route registrations. |
| [ISavedObjectsPointInTimeFinder](./kibana-plugin-core-server.isavedobjectspointintimefinder.md) | |
@ -113,9 +104,6 @@ The plugin integrates with the core system via lifecycle events: `setup`<!-- -->
| [IUiSettingsClient](./kibana-plugin-core-server.iuisettingsclient.md) | Server-side client that provides access to the advanced settings stored in elasticsearch. The settings provide control over the behavior of the Kibana application. For example, a user can specify how to display numeric or date fields. Users can adjust the settings via Management UI. |
| [KibanaRequestEvents](./kibana-plugin-core-server.kibanarequestevents.md) | Request events. |
| [KibanaRequestRoute](./kibana-plugin-core-server.kibanarequestroute.md) | Request specific route information exposed to a handler. |
| [LegacyAPICaller](./kibana-plugin-core-server.legacyapicaller.md) | |
| [LegacyCallAPIOptions](./kibana-plugin-core-server.legacycallapioptions.md) | The set of options that defines how API call should be made and result be processed. |
| [LegacyElasticsearchError](./kibana-plugin-core-server.legacyelasticsearcherror.md) | @<!-- -->deprecated. The new elasticsearch client doesn't wrap errors anymore. 7.16 |
| [LegacyRequest](./kibana-plugin-core-server.legacyrequest.md) | |
| [LoggerContextConfigInput](./kibana-plugin-core-server.loggercontextconfiginput.md) | |
| [LoggingServiceSetup](./kibana-plugin-core-server.loggingservicesetup.md) | Provides APIs to plugins for customizing the plugin's logger. |
@ -139,7 +127,7 @@ The plugin integrates with the core system via lifecycle events: `setup`<!-- -->
| [PrebootPlugin](./kibana-plugin-core-server.prebootplugin.md) | The interface that should be returned by a <code>PluginInitializer</code> for a <code>preboot</code> plugin. |
| [PrebootServicePreboot](./kibana-plugin-core-server.prebootservicepreboot.md) | Kibana Preboot Service allows to control the boot flow of Kibana. Preboot plugins can use it to hold the boot until certain condition is met. |
| [RegisterDeprecationsConfig](./kibana-plugin-core-server.registerdeprecationsconfig.md) | |
| [RequestHandlerContext](./kibana-plugin-core-server.requesthandlercontext.md) | Plugin specific context passed to a route handler.<!-- -->Provides the following clients and services: - [savedObjects.client](./kibana-plugin-core-server.savedobjectsclient.md) - Saved Objects client which uses the credentials of the incoming request - [savedObjects.typeRegistry](./kibana-plugin-core-server.isavedobjecttyperegistry.md) - Type registry containing all the registered types. - [elasticsearch.client](./kibana-plugin-core-server.iscopedclusterclient.md) - Elasticsearch data client which uses the credentials of the incoming request - [elasticsearch.legacy.client](./kibana-plugin-core-server.legacyscopedclusterclient.md) - The legacy Elasticsearch data client which uses the credentials of the incoming request - [uiSettings.client](./kibana-plugin-core-server.iuisettingsclient.md) - uiSettings client which uses the credentials of the incoming request |
| [RequestHandlerContext](./kibana-plugin-core-server.requesthandlercontext.md) | Plugin specific context passed to a route handler.<!-- -->Provides the following clients and services: - [savedObjects.client](./kibana-plugin-core-server.savedobjectsclient.md) - Saved Objects client which uses the credentials of the incoming request - [savedObjects.typeRegistry](./kibana-plugin-core-server.isavedobjecttyperegistry.md) - Type registry containing all the registered types. - [elasticsearch.client](./kibana-plugin-core-server.iscopedclusterclient.md) - Elasticsearch data client which uses the credentials of the incoming request - - The legacy Elasticsearch data client which uses the credentials of the incoming request - [uiSettings.client](./kibana-plugin-core-server.iuisettingsclient.md) - uiSettings client which uses the credentials of the incoming request |
| [ResolveCapabilitiesOptions](./kibana-plugin-core-server.resolvecapabilitiesoptions.md) | Defines a set of additional options for the <code>resolveCapabilities</code> method of [CapabilitiesStart](./kibana-plugin-core-server.capabilitiesstart.md)<!-- -->. |
| [RouteConfig](./kibana-plugin-core-server.routeconfig.md) | Route specific configuration. |
| [RouteConfigOptions](./kibana-plugin-core-server.routeconfigoptions.md) | Additional route options. |
@ -270,9 +258,6 @@ The plugin integrates with the core system via lifecycle events: `setup`<!-- -->
| [HttpResponsePayload](./kibana-plugin-core-server.httpresponsepayload.md) | Data send to the client as a response payload. |
| [IBasePath](./kibana-plugin-core-server.ibasepath.md) | Access or manipulate the Kibana base path[BasePath](./kibana-plugin-core-server.basepath.md) |
| [IContextProvider](./kibana-plugin-core-server.icontextprovider.md) | A function that returns a context value for a specific key of given context type. |
| [ILegacyClusterClient](./kibana-plugin-core-server.ilegacyclusterclient.md) | 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 <code>asScoped(...)</code>).<!-- -->See [LegacyClusterClient](./kibana-plugin-core-server.legacyclusterclient.md)<!-- -->. |
| [ILegacyCustomClusterClient](./kibana-plugin-core-server.ilegacycustomclusterclient.md) | Represents an Elasticsearch cluster API client created by a plugin. It allows to call API on behalf of the internal Kibana user and the actual user that is derived from the request headers (via <code>asScoped(...)</code>).<!-- -->See [LegacyClusterClient](./kibana-plugin-core-server.legacyclusterclient.md)<!-- -->. |
| [ILegacyScopedClusterClient](./kibana-plugin-core-server.ilegacyscopedclusterclient.md) | Serves the same purpose as "normal" <code>ClusterClient</code> but exposes additional <code>callAsCurrentUser</code> method that doesn't use credentials of the Kibana internal user (as <code>callAsInternalUser</code> does) to request Elasticsearch API, but rather passes HTTP headers extracted from the current user request to the API.<!-- -->See [LegacyScopedClusterClient](./kibana-plugin-core-server.legacyscopedclusterclient.md)<!-- -->. |
| [IsAuthenticated](./kibana-plugin-core-server.isauthenticated.md) | Returns authentication status for a request. |
| [ISavedObjectsExporter](./kibana-plugin-core-server.isavedobjectsexporter.md) | |
| [ISavedObjectsImporter](./kibana-plugin-core-server.isavedobjectsimporter.md) | |
@ -282,13 +267,10 @@ The plugin integrates with the core system via lifecycle events: `setup`<!-- -->
| [KibanaRequestRouteOptions](./kibana-plugin-core-server.kibanarequestrouteoptions.md) | Route options: If 'GET' or 'OPTIONS' method, body options won't be returned. |
| [KibanaResponseFactory](./kibana-plugin-core-server.kibanaresponsefactory.md) | Creates an object containing request response payload, HTTP headers, error details, and other data transmitted to the client. |
| [KnownHeaders](./kibana-plugin-core-server.knownheaders.md) | Set of well-known HTTP headers. |
| [LegacyElasticsearchClientConfig](./kibana-plugin-core-server.legacyelasticsearchclientconfig.md) | |
| [LifecycleResponseFactory](./kibana-plugin-core-server.lifecycleresponsefactory.md) | Creates an object containing redirection or error response with error details, HTTP headers, and other data transmitted to the client. |
| [LoggerConfigType](./kibana-plugin-core-server.loggerconfigtype.md) | |
| [MakeUsageFromSchema](./kibana-plugin-core-server.makeusagefromschema.md) | List of configuration values that will be exposed to usage collection. If parent node or actual config path is set to <code>true</code> then the actual value of these configs will be reoprted. If parent node or actual config path is set to <code>false</code> then the config will be reported as \[redacted\]. |
| [MetricsServiceStart](./kibana-plugin-core-server.metricsservicestart.md) | APIs to retrieves metrics gathered and exposed by the core platform. |
| [MIGRATION\_ASSISTANCE\_INDEX\_ACTION](./kibana-plugin-core-server.migration_assistance_index_action.md) | |
| [MIGRATION\_DEPRECATION\_LEVEL](./kibana-plugin-core-server.migration_deprecation_level.md) | |
| [MutatingOperationRefreshSetting](./kibana-plugin-core-server.mutatingoperationrefreshsetting.md) | Elasticsearch Refresh setting for mutating operation |
| [OnPostAuthHandler](./kibana-plugin-core-server.onpostauthhandler.md) | See [OnPostAuthToolkit](./kibana-plugin-core-server.onpostauthtoolkit.md)<!-- -->. |
| [OnPreAuthHandler](./kibana-plugin-core-server.onpreauthhandler.md) | See [OnPreAuthToolkit](./kibana-plugin-core-server.onpreauthtoolkit.md)<!-- -->. |

View file

@ -1,16 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [MIGRATION\_ASSISTANCE\_INDEX\_ACTION](./kibana-plugin-core-server.migration_assistance_index_action.md)
## MIGRATION\_ASSISTANCE\_INDEX\_ACTION type
> Warning: This API is now obsolete.
>
> 7.16
>
<b>Signature:</b>
```typescript
export declare type MIGRATION_ASSISTANCE_INDEX_ACTION = 'upgrade' | 'reindex';
```

View file

@ -1,16 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-server](./kibana-plugin-core-server.md) &gt; [MIGRATION\_DEPRECATION\_LEVEL](./kibana-plugin-core-server.migration_deprecation_level.md)
## MIGRATION\_DEPRECATION\_LEVEL type
> Warning: This API is now obsolete.
>
> 7.16
>
<b>Signature:</b>
```typescript
export declare type MIGRATION_DEPRECATION_LEVEL = 'none' | 'info' | 'warning' | 'critical';
```

View file

@ -17,9 +17,6 @@ core: {
};
elasticsearch: {
client: IScopedClusterClient;
legacy: {
client: ILegacyScopedClusterClient;
};
};
uiSettings: {
client: IUiSettingsClient;

View file

@ -6,7 +6,7 @@
Plugin specific context passed to a route handler.
Provides the following clients and services: - [savedObjects.client](./kibana-plugin-core-server.savedobjectsclient.md) - Saved Objects client which uses the credentials of the incoming request - [savedObjects.typeRegistry](./kibana-plugin-core-server.isavedobjecttyperegistry.md) - Type registry containing all the registered types. - [elasticsearch.client](./kibana-plugin-core-server.iscopedclusterclient.md) - Elasticsearch data client which uses the credentials of the incoming request - [elasticsearch.legacy.client](./kibana-plugin-core-server.legacyscopedclusterclient.md) - The legacy Elasticsearch data client which uses the credentials of the incoming request - [uiSettings.client](./kibana-plugin-core-server.iuisettingsclient.md) - uiSettings client which uses the credentials of the incoming request
Provides the following clients and services: - [savedObjects.client](./kibana-plugin-core-server.savedobjectsclient.md) - Saved Objects client which uses the credentials of the incoming request - [savedObjects.typeRegistry](./kibana-plugin-core-server.isavedobjecttyperegistry.md) - Type registry containing all the registered types. - [elasticsearch.client](./kibana-plugin-core-server.iscopedclusterclient.md) - Elasticsearch data client which uses the credentials of the incoming request - - The legacy Elasticsearch data client which uses the credentials of the incoming request - [uiSettings.client](./kibana-plugin-core-server.iuisettingsclient.md) - uiSettings client which uses the credentials of the incoming request
<b>Signature:</b>
@ -18,5 +18,5 @@ export interface RequestHandlerContext
| Property | Type | Description |
| --- | --- | --- |
| [core](./kibana-plugin-core-server.requesthandlercontext.core.md) | <code>{</code><br/><code> savedObjects: {</code><br/><code> client: SavedObjectsClientContract;</code><br/><code> typeRegistry: ISavedObjectTypeRegistry;</code><br/><code> getClient: (options?: SavedObjectsClientProviderOptions) =&gt; SavedObjectsClientContract;</code><br/><code> getExporter: (client: SavedObjectsClientContract) =&gt; ISavedObjectsExporter;</code><br/><code> getImporter: (client: SavedObjectsClientContract) =&gt; ISavedObjectsImporter;</code><br/><code> };</code><br/><code> elasticsearch: {</code><br/><code> client: IScopedClusterClient;</code><br/><code> legacy: {</code><br/><code> client: ILegacyScopedClusterClient;</code><br/><code> };</code><br/><code> };</code><br/><code> uiSettings: {</code><br/><code> client: IUiSettingsClient;</code><br/><code> };</code><br/><code> deprecations: {</code><br/><code> client: DeprecationsClient;</code><br/><code> };</code><br/><code> }</code> | |
| [core](./kibana-plugin-core-server.requesthandlercontext.core.md) | <code>{</code><br/><code> savedObjects: {</code><br/><code> client: SavedObjectsClientContract;</code><br/><code> typeRegistry: ISavedObjectTypeRegistry;</code><br/><code> getClient: (options?: SavedObjectsClientProviderOptions) =&gt; SavedObjectsClientContract;</code><br/><code> getExporter: (client: SavedObjectsClientContract) =&gt; ISavedObjectsExporter;</code><br/><code> getImporter: (client: SavedObjectsClientContract) =&gt; ISavedObjectsImporter;</code><br/><code> };</code><br/><code> elasticsearch: {</code><br/><code> client: IScopedClusterClient;</code><br/><code> };</code><br/><code> uiSettings: {</code><br/><code> client: IUiSettingsClient;</code><br/><code> };</code><br/><code> deprecations: {</code><br/><code> client: DeprecationsClient;</code><br/><code> };</code><br/><code> }</code> | |

View file

@ -10,7 +10,7 @@
start(core: CoreStart, { fieldFormats }: DataPluginStartDependencies): {
fieldFormats: FieldFormatsStart;
indexPatterns: {
indexPatternsServiceFactory: (savedObjectsClient: Pick<import("../../../core/server").SavedObjectsClient, "update" | "get" | "delete" | "create" | "bulkCreate" | "checkConflicts" | "find" | "bulkGet" | "resolve" | "collectMultiNamespaceReferences" | "updateObjectsSpaces" | "bulkUpdate" | "removeReferencesTo" | "openPointInTimeForType" | "closePointInTime" | "createPointInTimeFinder" | "errors">, elasticsearchClient: import("../../../core/server").ElasticsearchClient) => Promise<import(".").IndexPatternsService>;
indexPatternsServiceFactory: (savedObjectsClient: Pick<import("../../../core/server").SavedObjectsClient, "update" | "get" | "closePointInTime" | "create" | "delete" | "bulkCreate" | "checkConflicts" | "find" | "bulkGet" | "resolve" | "collectMultiNamespaceReferences" | "updateObjectsSpaces" | "bulkUpdate" | "removeReferencesTo" | "openPointInTimeForType" | "createPointInTimeFinder" | "errors">, elasticsearchClient: import("../../../core/server").ElasticsearchClient) => Promise<import(".").IndexPatternsService>;
};
search: ISearchStart<import("./search").IEsSearchRequest, import("./search").IEsSearchResponse<any>>;
};
@ -28,7 +28,7 @@ start(core: CoreStart, { fieldFormats }: DataPluginStartDependencies): {
`{
fieldFormats: FieldFormatsStart;
indexPatterns: {
indexPatternsServiceFactory: (savedObjectsClient: Pick<import("../../../core/server").SavedObjectsClient, "update" | "get" | "delete" | "create" | "bulkCreate" | "checkConflicts" | "find" | "bulkGet" | "resolve" | "collectMultiNamespaceReferences" | "updateObjectsSpaces" | "bulkUpdate" | "removeReferencesTo" | "openPointInTimeForType" | "closePointInTime" | "createPointInTimeFinder" | "errors">, elasticsearchClient: import("../../../core/server").ElasticsearchClient) => Promise<import(".").IndexPatternsService>;
indexPatternsServiceFactory: (savedObjectsClient: Pick<import("../../../core/server").SavedObjectsClient, "update" | "get" | "closePointInTime" | "create" | "delete" | "bulkCreate" | "checkConflicts" | "find" | "bulkGet" | "resolve" | "collectMultiNamespaceReferences" | "updateObjectsSpaces" | "bulkUpdate" | "removeReferencesTo" | "openPointInTimeForType" | "createPointInTimeFinder" | "errors">, elasticsearchClient: import("../../../core/server").ElasticsearchClient) => Promise<import(".").IndexPatternsService>;
};
search: ISearchStart<import("./search").IEsSearchRequest, import("./search").IEsSearchResponse<any>>;
}`

View file

@ -224,7 +224,6 @@
"deepmerge": "^4.2.2",
"del": "^5.1.0",
"elastic-apm-node": "^3.16.0",
"elasticsearch": "^16.7.0",
"execa": "^4.0.2",
"exit-hook": "^2.2.0",
"expiry-js": "0.1.7",
@ -737,10 +736,10 @@
"gulp": "4.0.2",
"gulp-babel": "^8.0.0",
"gulp-brotli": "^3.0.0",
"gulp-gzip": "^1.4.2",
"gulp-postcss": "^8.0.0",
"gulp-sourcemaps": "2.6.5",
"gulp-terser": "^2.0.1",
"gulp-gzip": "^1.4.2",
"gulp-zip": "^5.0.2",
"has-ansi": "^3.0.0",
"hdr-histogram-js": "^1.2.0",
@ -826,8 +825,8 @@
"tar-fs": "^2.1.0",
"tempy": "^0.3.0",
"terminal-link": "^2.1.1",
"terser-webpack-plugin": "^2.1.2",
"terser": "^5.7.1",
"terser-webpack-plugin": "^2.1.2",
"ts-loader": "^7.0.5",
"ts-morph": "^9.1.0",
"tsd": "^0.13.1",

View file

@ -44,43 +44,6 @@ describe('#elasticsearch', () => {
expect(client2).toBe(mockResult);
});
});
describe('#legacy', () => {
describe('#client', () => {
test('returns the results of coreStart.elasticsearch.legacy.client.asScoped', () => {
const request = httpServerMock.createKibanaRequest();
const coreStart = coreMock.createInternalStart();
const context = new CoreRouteHandlerContext(coreStart, request);
const client = context.elasticsearch.legacy.client;
expect(client).toBe(coreStart.elasticsearch.legacy.client.asScoped.mock.results[0].value);
});
test('lazily created', () => {
const request = httpServerMock.createKibanaRequest();
const coreStart = coreMock.createInternalStart();
const context = new CoreRouteHandlerContext(coreStart, request);
expect(coreStart.elasticsearch.legacy.client.asScoped).not.toHaveBeenCalled();
const client = context.elasticsearch.legacy.client;
expect(coreStart.elasticsearch.legacy.client.asScoped).toHaveBeenCalled();
expect(client).toBeDefined();
});
test('only creates one instance', () => {
const request = httpServerMock.createKibanaRequest();
const coreStart = coreMock.createInternalStart();
const context = new CoreRouteHandlerContext(coreStart, request);
const client1 = context.elasticsearch.legacy.client;
const client2 = context.elasticsearch.legacy.client;
expect(coreStart.elasticsearch.legacy.client.asScoped.mock.calls.length).toBe(1);
const mockResult = coreStart.elasticsearch.legacy.client.asScoped.mock.results[0].value;
expect(client1).toBe(mockResult);
expect(client2).toBe(mockResult);
});
});
});
});
describe('#savedObjects', () => {

View file

@ -15,19 +15,12 @@ import {
ISavedObjectTypeRegistry,
SavedObjectsClientProviderOptions,
} from './saved_objects';
import {
InternalElasticsearchServiceStart,
IScopedClusterClient,
LegacyScopedClusterClient,
} from './elasticsearch';
import { InternalElasticsearchServiceStart, IScopedClusterClient } from './elasticsearch';
import { InternalUiSettingsServiceStart, IUiSettingsClient } from './ui_settings';
import { DeprecationsClient, InternalDeprecationsServiceStart } from './deprecations';
class CoreElasticsearchRouteHandlerContext {
#client?: IScopedClusterClient;
#legacy?: {
client: Pick<LegacyScopedClusterClient, 'callAsInternalUser' | 'callAsCurrentUser'>;
};
constructor(
private readonly elasticsearchStart: InternalElasticsearchServiceStart,
@ -40,15 +33,6 @@ class CoreElasticsearchRouteHandlerContext {
}
return this.#client;
}
public get legacy() {
if (this.#legacy == null) {
this.#legacy = {
client: this.elasticsearchStart.legacy.client.asScoped(this.request),
};
}
return this.#legacy;
}
}
class CoreSavedObjectsRouteHandlerContext {

View file

@ -6,20 +6,23 @@
* Side Public License, v 1.
*/
import { Client, ApiResponse } from '@elastic/elasticsearch';
import type { Client, ApiResponse } from '@elastic/elasticsearch';
import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport';
import type { DeeplyMockedKeys } from '@kbn/utility-types/jest';
import { ElasticsearchClient } from './types';
import { ICustomClusterClient } from './cluster_client';
import { PRODUCT_RESPONSE_HEADER } from '../supported_server_response_check';
// use jest.requireActual() to prevent weird errors when people mock @elastic/elasticsearch
const { Client: UnmockedClient } = jest.requireActual('@elastic/elasticsearch');
const createInternalClientMock = (
res?: MockedTransportRequestPromise<unknown>
): DeeplyMockedKeys<Client> => {
// we mimic 'reflection' on a concrete instance of the client to generate the mocked functions.
const client = new Client({
const client = new UnmockedClient({
node: 'http://localhost',
}) as any;
});
const omittedProps = [
'_events',

View file

@ -9,14 +9,12 @@
import { BehaviorSubject } from 'rxjs';
import type { PublicMethodsOf } from '@kbn/utility-types';
import { ILegacyClusterClient, ILegacyCustomClusterClient } from './legacy';
import {
elasticsearchClientMock,
ClusterClientMock,
CustomClusterClientMock,
} from './client/mocks';
import { ElasticsearchClientConfig } from './client';
import { legacyClientMock } from './legacy/mocks';
import { ElasticsearchConfig } from './elasticsearch_config';
import { ElasticsearchService } from './elasticsearch_service';
import {
@ -32,8 +30,6 @@ type MockedElasticSearchServicePreboot = jest.Mocked<ElasticsearchServicePreboot
export interface MockedElasticSearchServiceSetup {
legacy: {
config$: BehaviorSubject<ElasticsearchConfig>;
createClient: jest.Mock<ILegacyCustomClusterClient, any>;
client: jest.Mocked<ILegacyClusterClient>;
};
}
@ -59,14 +55,8 @@ const createSetupContractMock = () => {
const setupContract: MockedElasticSearchServiceSetup = {
legacy: {
config$: new BehaviorSubject({} as ElasticsearchConfig),
createClient: jest.fn(),
client: legacyClientMock.createClusterClient(),
},
};
setupContract.legacy.createClient.mockReturnValue(legacyClientMock.createCustomClusterClient());
setupContract.legacy.client.asScoped.mockReturnValue(
legacyClientMock.createScopedClusterClient()
);
return setupContract;
};
@ -76,14 +66,9 @@ const createStartContractMock = () => {
createClient: jest.fn(),
legacy: {
config$: new BehaviorSubject({} as ElasticsearchConfig),
createClient: jest.fn(),
client: legacyClientMock.createClusterClient(),
},
};
startContract.legacy.createClient.mockReturnValue(legacyClientMock.createCustomClusterClient());
startContract.legacy.client.asScoped.mockReturnValue(
legacyClientMock.createScopedClusterClient()
);
startContract.createClient.mockImplementation(() =>
elasticsearchClientMock.createCustomClusterClient()
);
@ -92,11 +77,7 @@ const createStartContractMock = () => {
const createInternalPrebootContractMock = createPrebootContractMock;
type MockedInternalElasticSearchServiceSetup = jest.Mocked<
InternalElasticsearchServiceSetup & {
legacy: { client: jest.Mocked<ILegacyClusterClient> };
}
>;
type MockedInternalElasticSearchServiceSetup = jest.Mocked<InternalElasticsearchServiceSetup>;
const createInternalSetupContractMock = () => {
const setupContract: MockedInternalElasticSearchServiceSetup = {
esNodesCompatibility$: new BehaviorSubject<NodesVersionCompatibility>({
@ -113,9 +94,6 @@ const createInternalSetupContractMock = () => {
...createSetupContractMock().legacy,
},
};
setupContract.legacy.client.asScoped.mockReturnValue(
legacyClientMock.createScopedClusterClient()
);
return setupContract;
};
@ -144,10 +122,6 @@ export const elasticsearchServiceMock = {
createSetup: createSetupContractMock,
createInternalStart: createInternalStartContractMock,
createStart: createStartContractMock,
createLegacyClusterClient: legacyClientMock.createClusterClient,
createLegacyCustomClusterClient: legacyClientMock.createCustomClusterClient,
createLegacyScopedClusterClient: legacyClientMock.createScopedClusterClient,
createLegacyElasticsearchClient: legacyClientMock.createElasticsearchClient,
...elasticsearchClientMock,
};

View file

@ -6,8 +6,5 @@
* Side Public License, v 1.
*/
export const MockLegacyClusterClient = jest.fn();
jest.mock('./legacy/cluster_client', () => ({ LegacyClusterClient: MockLegacyClusterClient }));
export const MockClusterClient = jest.fn();
jest.mock('./client/cluster_client', () => ({ ClusterClient: MockClusterClient }));

View file

@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
import { MockLegacyClusterClient, MockClusterClient } from './elasticsearch_service.test.mocks';
import { MockClusterClient } from './elasticsearch_service.test.mocks';
import { BehaviorSubject } from 'rxjs';
import { first } from 'rxjs/operators';
import { REPO_ROOT } from '@kbn/dev-utils';
@ -18,7 +18,6 @@ import { httpServiceMock } from '../http/http_service.mock';
import { executionContextServiceMock } from '../execution_context/execution_context_service.mock';
import { configSchema, ElasticsearchConfig } from './elasticsearch_config';
import { ElasticsearchService } from './elasticsearch_service';
import { elasticsearchServiceMock } from './elasticsearch_service.mock';
import { elasticsearchClientMock } from './client/mocks';
import { duration } from 'moment';
@ -37,9 +36,7 @@ let coreContext: CoreContext;
const logger = loggingSystemMock.create();
let mockClusterClientInstance: ReturnType<typeof elasticsearchClientMock.createCustomClusterClient>;
let mockLegacyClusterClientInstance: ReturnType<
typeof elasticsearchServiceMock.createLegacyCustomClusterClient
>;
let mockConfig$: BehaviorSubject<any>;
beforeEach(() => {
env = Env.createDefault(REPO_ROOT, getEnvOptions());
@ -58,11 +55,7 @@ beforeEach(() => {
coreContext = { coreId: Symbol(), env, logger, configService: configService as any };
elasticsearchService = new ElasticsearchService(coreContext);
MockLegacyClusterClient.mockClear();
MockClusterClient.mockClear();
mockLegacyClusterClientInstance = elasticsearchServiceMock.createLegacyCustomClusterClient();
MockLegacyClusterClient.mockImplementation(() => mockLegacyClusterClientInstance);
mockClusterClientInstance = elasticsearchClientMock.createCustomClusterClient();
MockClusterClient.mockImplementation(() => mockClusterClientInstance);
});
@ -162,141 +155,6 @@ describe('#setup', () => {
);
});
it('returns legacy elasticsearch client as a part of the contract', async () => {
const setupContract = await elasticsearchService.setup(setupDeps);
const client = setupContract.legacy.client;
expect(mockLegacyClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(0);
await client.callAsInternalUser('any');
expect(mockLegacyClusterClientInstance.callAsInternalUser).toHaveBeenCalledTimes(1);
});
describe('#createLegacyClient', () => {
it('allows to specify config properties', async () => {
const setupContract = await elasticsearchService.setup(setupDeps);
// reset all mocks called during setup phase
MockLegacyClusterClient.mockClear();
const customConfig = { keepAlive: true };
const clusterClient = setupContract.legacy.createClient('some-custom-type', customConfig);
expect(clusterClient).toBe(mockLegacyClusterClientInstance);
expect(MockLegacyClusterClient).toHaveBeenCalledWith(
expect.objectContaining(customConfig),
expect.objectContaining({ context: ['elasticsearch'] }),
'some-custom-type',
expect.any(Function)
);
});
it('falls back to elasticsearch default config values if property not specified', async () => {
const setupContract = await elasticsearchService.setup(setupDeps);
// reset all mocks called during setup phase
MockLegacyClusterClient.mockClear();
const customConfig = {
hosts: ['http://8.8.8.8'],
logQueries: true,
ssl: { certificate: 'certificate-value' },
};
setupContract.legacy.createClient('some-custom-type', customConfig);
const config = MockLegacyClusterClient.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",
},
}
`);
});
it('falls back to elasticsearch config if custom config not passed', async () => {
const setupContract = await elasticsearchService.setup(setupDeps);
// reset all mocks called during setup phase
MockLegacyClusterClient.mockClear();
setupContract.legacy.createClient('another-type');
const config = MockLegacyClusterClient.mock.calls[0][0];
expect(config).toMatchInlineSnapshot(`
Object {
"healthCheckDelay": "PT0.01S",
"hosts": Array [
"http://1.2.3.4",
],
"requestHeadersWhitelist": Array [
undefined,
],
"ssl": Object {
"alwaysPresentCertificate": undefined,
"certificate": undefined,
"certificateAuthorities": undefined,
"key": undefined,
"keyPassphrase": undefined,
"verificationMode": "none",
},
}
`);
});
it('does not merge elasticsearch hosts if custom config overrides', async () => {
configService.atPath.mockReturnValueOnce(
new BehaviorSubject({
hosts: ['http://1.2.3.4', 'http://9.8.7.6'],
healthCheck: {
delay: duration(2000),
},
ssl: {
verificationMode: 'none',
},
} as any)
);
elasticsearchService = new ElasticsearchService(coreContext);
const setupContract = await elasticsearchService.setup(setupDeps);
// reset all mocks called during setup phase
MockLegacyClusterClient.mockClear();
const customConfig = {
hosts: ['http://8.8.8.8'],
logQueries: true,
ssl: { certificate: 'certificate-value' },
};
setupContract.legacy.createClient('some-custom-type', customConfig);
const config = MockLegacyClusterClient.mock.calls[0][0];
expect(config).toMatchInlineSnapshot(`
Object {
"healthCheckDelay": "PT2S",
"hosts": Array [
"http://8.8.8.8",
],
"logQueries": true,
"requestHeadersWhitelist": Array [
undefined,
],
"ssl": Object {
"certificate": "certificate-value",
"verificationMode": "none",
},
}
`);
});
});
it('esNodeVersionCompatibility$ only starts polling when subscribed to', async (done) => {
const mockedClient = mockClusterClientInstance.asInternalUser;
mockedClient.nodes.info.mockImplementation(() =>
@ -419,7 +277,6 @@ describe('#stop', () => {
await elasticsearchService.start();
await elasticsearchService.stop();
expect(mockLegacyClusterClientInstance.close).toHaveBeenCalledTimes(1);
expect(mockClusterClientInstance.close).toHaveBeenCalledTimes(1);
});

View file

@ -13,11 +13,7 @@ import { merge } from '@kbn/std';
import { CoreService } from '../../types';
import { CoreContext } from '../core_context';
import { Logger } from '../logging';
import {
LegacyClusterClient,
ILegacyCustomClusterClient,
LegacyElasticsearchClientConfig,
} from './legacy';
import { ClusterClient, ElasticsearchClientConfig } from './client';
import { ElasticsearchConfig, ElasticsearchConfigType } from './elasticsearch_config';
import type { InternalHttpServiceSetup, GetAuthHeaders } from '../http';
@ -45,12 +41,6 @@ export class ElasticsearchService
private getAuthHeaders?: GetAuthHeaders;
private executionContextClient?: IExecutionContext;
private createLegacyCustomClient?: (
type: string,
clientConfig?: Partial<LegacyElasticsearchClientConfig>
) => ILegacyCustomClusterClient;
private legacyClient?: LegacyClusterClient;
private client?: ClusterClient;
constructor(private readonly coreContext: CoreContext) {
@ -84,7 +74,6 @@ export class ElasticsearchService
this.getAuthHeaders = deps.http.getAuthHeaders;
this.executionContextClient = deps.executionContext;
this.legacyClient = this.createLegacyClusterClient('data', config);
this.client = this.createClusterClient('data', config);
const esNodesCompatibility$ = pollEsNodesVersion({
@ -95,23 +84,16 @@ export class ElasticsearchService
kibanaVersion: this.kibanaVersion,
}).pipe(takeUntil(this.stop$), shareReplay({ refCount: true, bufferSize: 1 }));
this.createLegacyCustomClient = (type, clientConfig = {}) => {
const finalConfig = merge({}, config, clientConfig);
return this.createLegacyClusterClient(type, finalConfig);
};
return {
legacy: {
config$: this.config$,
client: this.legacyClient,
createClient: this.createLegacyCustomClient,
},
esNodesCompatibility$,
status$: calculateStatus$(esNodesCompatibility$),
};
}
public async start(): Promise<InternalElasticsearchServiceStart> {
if (!this.legacyClient || !this.createLegacyCustomClient) {
if (!this.client) {
throw new Error('ElasticsearchService needs to be setup before calling start');
}
@ -121,8 +103,6 @@ export class ElasticsearchService
createClient: (type, clientConfig) => this.createClusterClient(type, config, clientConfig),
legacy: {
config$: this.config$,
client: this.legacyClient,
createClient: this.createLegacyCustomClient,
},
};
}
@ -133,9 +113,6 @@ export class ElasticsearchService
if (this.client) {
await this.client.close();
}
if (this.legacyClient) {
this.legacyClient.close();
}
}
private createClusterClient(
@ -152,13 +129,4 @@ export class ElasticsearchService
() => this.executionContextClient?.getAsHeader()
);
}
private createLegacyClusterClient(type: string, config: LegacyElasticsearchClientConfig) {
return new LegacyClusterClient(
config,
this.coreContext.logger.get('elasticsearch'),
type,
this.getAuthHeaders
);
}
}

View file

@ -22,7 +22,6 @@ export type {
ScopeableRequest,
ElasticsearchConfigPreboot,
} from './types';
export * from './legacy';
export type {
IClusterClient,
ICustomClusterClient,

View file

@ -1,392 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import {
Client,
GenericParams,
// root params
BulkIndexDocumentsParams,
ClearScrollParams,
CountParams,
CreateDocumentParams,
DeleteDocumentParams,
DeleteDocumentByQueryParams,
DeleteScriptParams,
DeleteTemplateParams,
ExistsParams,
ExplainParams,
FieldStatsParams,
GetParams,
GetResponse,
GetScriptParams,
GetSourceParams,
GetTemplateParams,
IndexDocumentParams,
InfoParams,
MGetParams,
MSearchParams,
MSearchTemplateParams,
MTermVectorsParams,
PingParams,
PutScriptParams,
PutTemplateParams,
ReindexParams,
ReindexRethrottleParams,
RenderSearchTemplateParams,
ScrollParams,
SearchParams,
SearchShardsParams,
SearchTemplateParams,
SuggestParams,
TermvectorsParams,
UpdateDocumentParams,
UpdateDocumentByQueryParams,
MGetResponse,
MSearchResponse,
SearchResponse,
// cat
CatAliasesParams,
CatAllocationParams,
CatFielddataParams,
CatHealthParams,
CatHelpParams,
CatIndicesParams,
CatCommonParams,
CatRecoveryParams,
CatSegmentsParams,
CatShardsParams,
CatSnapshotsParams,
CatTasksParams,
CatThreadPoolParams,
// cluster
ClusterAllocationExplainParams,
ClusterGetSettingsParams,
ClusterHealthParams,
ClusterPendingTasksParams,
ClusterPutSettingsParams,
ClusterRerouteParams,
ClusterStateParams,
ClusterStatsParams,
// indices
IndicesAnalyzeParams,
IndicesClearCacheParams,
IndicesCloseParams,
IndicesCreateParams,
IndicesDeleteParams,
IndicesDeleteAliasParams,
IndicesDeleteTemplateParams,
IndicesExistsParams,
IndicesExistsAliasParams,
IndicesExistsTemplateParams,
IndicesExistsTypeParams,
IndicesFlushParams,
IndicesFlushSyncedParams,
IndicesForcemergeParams,
IndicesGetParams,
IndicesGetAliasParams,
IndicesGetFieldMappingParams,
IndicesGetMappingParams,
IndicesGetSettingsParams,
IndicesGetTemplateParams,
IndicesGetUpgradeParams,
IndicesOpenParams,
IndicesPutAliasParams,
IndicesPutMappingParams,
IndicesPutSettingsParams,
IndicesPutTemplateParams,
IndicesRecoveryParams,
IndicesRefreshParams,
IndicesRolloverParams,
IndicesSegmentsParams,
IndicesShardStoresParams,
IndicesShrinkParams,
IndicesStatsParams,
IndicesUpdateAliasesParams,
IndicesUpgradeParams,
IndicesValidateQueryParams,
// ingest
IngestDeletePipelineParams,
IngestGetPipelineParams,
IngestPutPipelineParams,
IngestSimulateParams,
// nodes
NodesHotThreadsParams,
NodesInfoParams,
NodesStatsParams,
// snapshot
SnapshotCreateParams,
SnapshotCreateRepositoryParams,
SnapshotDeleteParams,
SnapshotDeleteRepositoryParams,
SnapshotGetParams,
SnapshotGetRepositoryParams,
SnapshotRestoreParams,
SnapshotStatusParams,
SnapshotVerifyRepositoryParams,
// tasks
TasksCancelParams,
TasksGetParams,
TasksListParams,
} from 'elasticsearch';
/**
* The set of options that defines how API call should be made and result be
* processed.
*
* @public
* @deprecated
* @removeBy 7.16
*/
export interface LegacyCallAPIOptions {
/**
* Indicates whether `401 Unauthorized` errors returned from the Elasticsearch API
* should be wrapped into `Boom` error instances with properly set `WWW-Authenticate`
* header that could have been returned by the API itself. If API didn't specify that
* then `Basic realm="Authorization Required"` is used as `WWW-Authenticate`.
*/
wrap401Errors?: boolean;
/**
* A signal object that allows you to abort the request via an AbortController object.
*/
signal?: AbortSignal;
}
/**
* @deprecated
* @removeBy 7.16
* @public
* */
export interface LegacyAPICaller {
/* eslint-disable */
(endpoint: 'bulk', params: BulkIndexDocumentsParams, options?: LegacyCallAPIOptions): ReturnType<Client['bulk']>;
(endpoint: 'clearScroll', params: ClearScrollParams, options?: LegacyCallAPIOptions): ReturnType<Client['clearScroll']>;
(endpoint: 'count', params: CountParams, options?: LegacyCallAPIOptions): ReturnType<Client['count']>;
(endpoint: 'create', params: CreateDocumentParams, options?: LegacyCallAPIOptions): ReturnType<Client['create']>;
(endpoint: 'delete', params: DeleteDocumentParams, options?: LegacyCallAPIOptions): ReturnType<Client['delete']>;
(endpoint: 'deleteByQuery', params: DeleteDocumentByQueryParams, options?: LegacyCallAPIOptions): ReturnType<Client['deleteByQuery']>;
(endpoint: 'deleteScript', params: DeleteScriptParams, options?: LegacyCallAPIOptions): ReturnType<Client['deleteScript']>;
(endpoint: 'deleteTemplate', params: DeleteTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['deleteTemplate']>;
(endpoint: 'exists', params: ExistsParams, options?: LegacyCallAPIOptions): ReturnType<Client['exists']>;
(endpoint: 'explain', params: ExplainParams, options?: LegacyCallAPIOptions): ReturnType<Client['explain']>;
(endpoint: 'fieldStats', params: FieldStatsParams, options?: LegacyCallAPIOptions): ReturnType<Client['fieldStats']>;
// Generic types cannot be properly looked up with ReturnType. Hard code these explicitly.
<T>(endpoint: 'get', params: GetParams, options?: LegacyCallAPIOptions): Promise<GetResponse<T>>;
(endpoint: 'getScript', params: GetScriptParams, options?: LegacyCallAPIOptions): ReturnType<Client['getScript']>;
(endpoint: 'getSource', params: GetSourceParams, options?: LegacyCallAPIOptions): ReturnType<Client['getSource']>;
(endpoint: 'getTemplate', params: GetTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['getTemplate']>;
// Generic types cannot be properly looked up with ReturnType. Hard code these explicitly.
<T>(endpoint: 'index', params: IndexDocumentParams<T>, options?: LegacyCallAPIOptions): ReturnType<Client['index']>;
(endpoint: 'info', params: InfoParams, options?: LegacyCallAPIOptions): ReturnType<Client['info']>;
// Generic types cannot be properly looked up with ReturnType. Hard code these explicitly.
<T>(endpoint: 'mget', params: MGetParams, options?: LegacyCallAPIOptions): Promise<MGetResponse<T>>;
<T>(endpoint: 'msearch', params: MSearchParams, options?: LegacyCallAPIOptions): Promise<MSearchResponse<T>>;
<T>(endpoint: 'msearchTemplate', params: MSearchTemplateParams, options?: LegacyCallAPIOptions): Promise<MSearchResponse<T>>;
(endpoint: 'mtermvectors', params: MTermVectorsParams, options?: LegacyCallAPIOptions): ReturnType<Client['mtermvectors']>;
(endpoint: 'ping', params: PingParams, options?: LegacyCallAPIOptions): ReturnType<Client['ping']>;
(endpoint: 'putScript', params: PutScriptParams, options?: LegacyCallAPIOptions): ReturnType<Client['putScript']>;
(endpoint: 'putTemplate', params: PutTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['putTemplate']>;
(endpoint: 'reindex', params: ReindexParams, options?: LegacyCallAPIOptions): ReturnType<Client['reindex']>;
(endpoint: 'reindexRethrottle', params: ReindexRethrottleParams, options?: LegacyCallAPIOptions): ReturnType<Client['reindexRethrottle']>;
(endpoint: 'renderSearchTemplate', params: RenderSearchTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['renderSearchTemplate']>;
// Generic types cannot be properly looked up with ReturnType. Hard code these explicitly.
<T>(endpoint: 'scroll', params: ScrollParams, options?: LegacyCallAPIOptions): Promise<SearchResponse<T>>;
<T>(endpoint: 'search', params: SearchParams, options?: LegacyCallAPIOptions): Promise<SearchResponse<T>>;
(endpoint: 'searchShards', params: SearchShardsParams, options?: LegacyCallAPIOptions): ReturnType<Client['searchShards']>;
(endpoint: 'searchTemplate', params: SearchTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['searchTemplate']>;
(endpoint: 'suggest', params: SuggestParams, options?: LegacyCallAPIOptions): ReturnType<Client['suggest']>;
(endpoint: 'termvectors', params: TermvectorsParams, options?: LegacyCallAPIOptions): ReturnType<Client['termvectors']>;
(endpoint: 'update', params: UpdateDocumentParams, options?: LegacyCallAPIOptions): ReturnType<Client['update']>;
(endpoint: 'updateByQuery', params: UpdateDocumentByQueryParams, options?: LegacyCallAPIOptions): ReturnType<Client['updateByQuery']>;
// cat namespace
(endpoint: 'cat.aliases', params: CatAliasesParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['aliases']>;
(endpoint: 'cat.allocation', params: CatAllocationParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['allocation']>;
(endpoint: 'cat.count', params: CatAllocationParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['count']>;
(endpoint: 'cat.fielddata', params: CatFielddataParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['fielddata']>;
(endpoint: 'cat.health', params: CatHealthParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['health']>;
(endpoint: 'cat.help', params: CatHelpParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['help']>;
(endpoint: 'cat.indices', params: CatIndicesParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['indices']>;
(endpoint: 'cat.master', params: CatCommonParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['master']>;
(endpoint: 'cat.nodeattrs', params: CatCommonParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['nodeattrs']>;
(endpoint: 'cat.nodes', params: CatCommonParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['nodes']>;
(endpoint: 'cat.pendingTasks', params: CatCommonParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['pendingTasks']>;
(endpoint: 'cat.plugins', params: CatCommonParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['plugins']>;
(endpoint: 'cat.recovery', params: CatRecoveryParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['recovery']>;
(endpoint: 'cat.repositories', params: CatCommonParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['repositories']>;
(endpoint: 'cat.segments', params: CatSegmentsParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['segments']>;
(endpoint: 'cat.shards', params: CatShardsParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['shards']>;
(endpoint: 'cat.snapshots', params: CatSnapshotsParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['snapshots']>;
(endpoint: 'cat.tasks', params: CatTasksParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['tasks']>;
(endpoint: 'cat.threadPool', params: CatThreadPoolParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['threadPool']>;
// cluster namespace
(endpoint: 'cluster.allocationExplain', params: ClusterAllocationExplainParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['allocationExplain']>;
(endpoint: 'cluster.getSettings', params: ClusterGetSettingsParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['getSettings']>;
(endpoint: 'cluster.health', params: ClusterHealthParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['health']>;
(endpoint: 'cluster.pendingTasks', params: ClusterPendingTasksParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['pendingTasks']>;
(endpoint: 'cluster.putSettings', params: ClusterPutSettingsParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['putSettings']>;
(endpoint: 'cluster.reroute', params: ClusterRerouteParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['reroute']>;
(endpoint: 'cluster.state', params: ClusterStateParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['state']>;
(endpoint: 'cluster.stats', params: ClusterStatsParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['stats']>;
// indices namespace
(endpoint: 'indices.analyze', params: IndicesAnalyzeParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['analyze']>;
(endpoint: 'indices.clearCache', params: IndicesClearCacheParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['clearCache']>;
(endpoint: 'indices.close', params: IndicesCloseParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['close']>;
(endpoint: 'indices.create', params: IndicesCreateParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['create']>;
(endpoint: 'indices.delete', params: IndicesDeleteParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['delete']>;
(endpoint: 'indices.deleteAlias', params: IndicesDeleteAliasParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['deleteAlias']>;
(endpoint: 'indices.deleteTemplate', params: IndicesDeleteTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['deleteTemplate']>;
(endpoint: 'indices.exists', params: IndicesExistsParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['exists']>;
(endpoint: 'indices.existsAlias', params: IndicesExistsAliasParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['existsAlias']>;
(endpoint: 'indices.existsTemplate', params: IndicesExistsTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['existsTemplate']>;
(endpoint: 'indices.existsType', params: IndicesExistsTypeParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['existsType']>;
(endpoint: 'indices.flush', params: IndicesFlushParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['flush']>;
(endpoint: 'indices.flushSynced', params: IndicesFlushSyncedParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['flushSynced']>;
(endpoint: 'indices.forcemerge', params: IndicesForcemergeParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['forcemerge']>;
(endpoint: 'indices.get', params: IndicesGetParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['get']>;
(endpoint: 'indices.getAlias', params: IndicesGetAliasParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['getAlias']>;
(endpoint: 'indices.getFieldMapping', params: IndicesGetFieldMappingParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['getFieldMapping']>;
(endpoint: 'indices.getMapping', params: IndicesGetMappingParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['getMapping']>;
(endpoint: 'indices.getSettings', params: IndicesGetSettingsParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['getSettings']>;
(endpoint: 'indices.getTemplate', params: IndicesGetTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['getTemplate']>;
(endpoint: 'indices.getUpgrade', params: IndicesGetUpgradeParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['getUpgrade']>;
(endpoint: 'indices.open', params: IndicesOpenParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['open']>;
(endpoint: 'indices.putAlias', params: IndicesPutAliasParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['putAlias']>;
(endpoint: 'indices.putMapping', params: IndicesPutMappingParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['putMapping']>;
(endpoint: 'indices.putSettings', params: IndicesPutSettingsParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['putSettings']>;
(endpoint: 'indices.putTemplate', params: IndicesPutTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['putTemplate']>;
(endpoint: 'indices.recovery', params: IndicesRecoveryParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['recovery']>;
(endpoint: 'indices.refresh', params: IndicesRefreshParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['refresh']>;
(endpoint: 'indices.rollover', params: IndicesRolloverParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['rollover']>;
(endpoint: 'indices.segments', params: IndicesSegmentsParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['segments']>;
(endpoint: 'indices.shardStores', params: IndicesShardStoresParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['shardStores']>;
(endpoint: 'indices.shrink', params: IndicesShrinkParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['shrink']>;
(endpoint: 'indices.stats', params: IndicesStatsParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['stats']>;
(endpoint: 'indices.updateAliases', params: IndicesUpdateAliasesParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['updateAliases']>;
(endpoint: 'indices.upgrade', params: IndicesUpgradeParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['upgrade']>;
(endpoint: 'indices.validateQuery', params: IndicesValidateQueryParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['validateQuery']>;
// ingest namepsace
(endpoint: 'ingest.deletePipeline', params: IngestDeletePipelineParams, options?: LegacyCallAPIOptions): ReturnType<Client['ingest']['deletePipeline']>;
(endpoint: 'ingest.getPipeline', params: IngestGetPipelineParams, options?: LegacyCallAPIOptions): ReturnType<Client['ingest']['getPipeline']>;
(endpoint: 'ingest.putPipeline', params: IngestPutPipelineParams, options?: LegacyCallAPIOptions): ReturnType<Client['ingest']['putPipeline']>;
(endpoint: 'ingest.simulate', params: IngestSimulateParams, options?: LegacyCallAPIOptions): ReturnType<Client['ingest']['simulate']>;
// nodes namespace
(endpoint: 'nodes.hotThreads', params: NodesHotThreadsParams, options?: LegacyCallAPIOptions): ReturnType<Client['nodes']['hotThreads']>;
(endpoint: 'nodes.info', params: NodesInfoParams, options?: LegacyCallAPIOptions): ReturnType<Client['nodes']['info']>;
(endpoint: 'nodes.stats', params: NodesStatsParams, options?: LegacyCallAPIOptions): ReturnType<Client['nodes']['stats']>;
// snapshot namespace
(endpoint: 'snapshot.create', params: SnapshotCreateParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['create']>;
(endpoint: 'snapshot.createRepository', params: SnapshotCreateRepositoryParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['createRepository']>;
(endpoint: 'snapshot.delete', params: SnapshotDeleteParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['delete']>;
(endpoint: 'snapshot.deleteRepository', params: SnapshotDeleteRepositoryParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['deleteRepository']>;
(endpoint: 'snapshot.get', params: SnapshotGetParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['get']>;
(endpoint: 'snapshot.getRepository', params: SnapshotGetRepositoryParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['getRepository']>;
(endpoint: 'snapshot.restore', params: SnapshotRestoreParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['restore']>;
(endpoint: 'snapshot.status', params: SnapshotStatusParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['status']>;
(endpoint: 'snapshot.verifyRepository', params: SnapshotVerifyRepositoryParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['verifyRepository']>;
// tasks namespace
(endpoint: 'tasks.cancel', params: TasksCancelParams, options?: LegacyCallAPIOptions): ReturnType<Client['tasks']['cancel']>;
(endpoint: 'tasks.get', params: TasksGetParams, options?: LegacyCallAPIOptions): ReturnType<Client['tasks']['get']>;
(endpoint: 'tasks.list', params: TasksListParams, options?: LegacyCallAPIOptions): ReturnType<Client['tasks']['list']>;
// other APIs accessed via transport.request
(endpoint: 'transport.request', clientParams: AssistantAPIClientParams, options?: LegacyCallAPIOptions): Promise<
AssistanceAPIResponse
>;
(endpoint: 'transport.request', clientParams: DeprecationAPIClientParams, options?: LegacyCallAPIOptions): Promise<
DeprecationAPIResponse
>;
// Catch-all definition
<T = any>(endpoint: string, clientParams?: Record<string, any>, options?: LegacyCallAPIOptions): Promise<T>;
/* eslint-enable */
}
/**
* @deprecated
* @removeBy 7.16
* @public
* */
export interface AssistantAPIClientParams extends GenericParams {
path: '/_migration/assistance';
method: 'GET';
}
/**
* @deprecated
* @removeBy 7.16
* @public
* */
export type MIGRATION_ASSISTANCE_INDEX_ACTION = 'upgrade' | 'reindex';
/**
* @deprecated
* @removeBy 7.16
* @public
* */
export type MIGRATION_DEPRECATION_LEVEL = 'none' | 'info' | 'warning' | 'critical';
/**
* @deprecated
* @removeBy 7.16
* @public
* */
export interface AssistanceAPIResponse {
indices: {
[indexName: string]: {
action_required: MIGRATION_ASSISTANCE_INDEX_ACTION;
};
};
}
/**
* @deprecated
* @removeBy 7.16
* @public
* */
export interface DeprecationAPIClientParams extends GenericParams {
path: '/_migration/deprecations';
method: 'GET';
}
/**
* @deprecated
* @removeBy 7.16
* @public
* */
export interface DeprecationInfo {
level: MIGRATION_DEPRECATION_LEVEL;
message: string;
url: string;
details?: string;
}
/**
* @deprecated
* @removeBy 7.16
* @public
* */
export interface IndexSettingsDeprecationInfo {
[indexName: string]: DeprecationInfo[];
}
/**
* @deprecated
* @removeBy 7.16
* @public
* */
export interface DeprecationAPIResponse {
cluster_settings: DeprecationInfo[];
ml_settings: DeprecationInfo[];
node_settings: DeprecationInfo[];
index_settings: IndexSettingsDeprecationInfo;
}

View file

@ -1,27 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
export const MockClient = jest.fn();
jest.mock('elasticsearch', () => {
const original = jest.requireActual('elasticsearch');
return {
...original,
Client: MockClient,
};
});
export const MockScopedClusterClient = jest.fn();
jest.mock('./scoped_cluster_client', () => ({
LegacyScopedClusterClient: MockScopedClusterClient,
}));
export const mockParseElasticsearchClientConfig = jest.fn();
jest.mock('./elasticsearch_client_config', () => ({
parseElasticsearchClientConfig: mockParseElasticsearchClientConfig,
}));

View file

@ -1,547 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { ElasticsearchConfig } from '../elasticsearch_config';
import {
MockClient,
mockParseElasticsearchClientConfig,
MockScopedClusterClient,
} from './cluster_client.test.mocks';
import { errors } from 'elasticsearch';
import { get } from 'lodash';
import { Logger } from '../../logging';
import { loggingSystemMock } from '../../logging/logging_system.mock';
import { httpServerMock } from '../../http/http_server.mocks';
import { LegacyClusterClient } from './cluster_client';
const logger = loggingSystemMock.create();
afterEach(() => jest.clearAllMocks());
test('#constructor creates client with parsed config', () => {
const mockEsClientConfig = { apiVersion: 'es-client-master' };
mockParseElasticsearchClientConfig.mockReturnValue(mockEsClientConfig);
const mockEsConfig = { apiVersion: 'es-version' } as any;
const mockLogger = logger.get();
const clusterClient = new LegacyClusterClient(mockEsConfig, mockLogger, 'custom-type');
expect(clusterClient).toBeDefined();
expect(mockParseElasticsearchClientConfig).toHaveBeenCalledTimes(1);
expect(mockParseElasticsearchClientConfig).toHaveBeenLastCalledWith(
mockEsConfig,
mockLogger,
'custom-type'
);
expect(MockClient).toHaveBeenCalledTimes(1);
expect(MockClient).toHaveBeenCalledWith(mockEsClientConfig);
});
describe('#callAsInternalUser', () => {
let mockEsClientInstance: {
close: jest.Mock;
ping: jest.Mock;
security: { authenticate: jest.Mock };
};
let clusterClient: LegacyClusterClient;
beforeEach(() => {
mockEsClientInstance = {
close: jest.fn(),
ping: jest.fn(),
security: { authenticate: jest.fn() },
};
MockClient.mockImplementation(() => mockEsClientInstance);
clusterClient = new LegacyClusterClient(
{ apiVersion: 'es-version' } as any,
logger.get(),
'custom-type'
);
});
test('fails if cluster client is closed', async () => {
clusterClient.close();
await expect(
clusterClient.callAsInternalUser('ping', {})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Cluster client cannot be used after it has been closed."`
);
});
test('fails if endpoint is invalid', async () => {
await expect(
clusterClient.callAsInternalUser('pong', {})
).rejects.toThrowErrorMatchingInlineSnapshot(`"called with an invalid endpoint: pong"`);
});
test('correctly deals with top level endpoint', async () => {
const mockResponse = { data: 'ping' };
const mockParams = { param: 'ping' };
mockEsClientInstance.ping.mockImplementation(function mockCall(this: any) {
return Promise.resolve({
context: this,
response: mockResponse,
});
});
const mockResult = await clusterClient.callAsInternalUser('ping', mockParams);
expect(mockResult.response).toBe(mockResponse);
expect(mockResult.context).toBe(mockEsClientInstance);
expect(mockEsClientInstance.ping).toHaveBeenCalledTimes(1);
expect(mockEsClientInstance.ping).toHaveBeenLastCalledWith(mockParams);
});
test('sets the authorization header when a service account token is configured', async () => {
clusterClient = new LegacyClusterClient(
{ apiVersion: 'es-version', serviceAccountToken: 'ABC123' } as any,
logger.get(),
'custom-type'
);
const mockResponse = { data: 'ping' };
const mockParams = { param: 'ping' };
mockEsClientInstance.ping.mockImplementation(function mockCall(this: any) {
return Promise.resolve({
context: this,
response: mockResponse,
});
});
await clusterClient.callAsInternalUser('ping', mockParams);
expect(mockEsClientInstance.ping).toHaveBeenCalledWith({
headers: { authorization: 'Bearer ABC123' },
param: 'ping',
});
});
test('correctly deals with nested endpoint', async () => {
const mockResponse = { data: 'authenticate' };
const mockParams = { param: 'authenticate' };
mockEsClientInstance.security.authenticate.mockImplementation(function mockCall(this: any) {
return Promise.resolve({
context: this,
response: mockResponse,
});
});
const mockResult = await clusterClient.callAsInternalUser('security.authenticate', mockParams);
expect(mockResult.response).toBe(mockResponse);
expect(mockResult.context).toBe(mockEsClientInstance.security);
expect(mockEsClientInstance.security.authenticate).toHaveBeenCalledTimes(1);
expect(mockEsClientInstance.security.authenticate).toHaveBeenLastCalledWith(mockParams);
});
test('does not wrap errors if `wrap401Errors` is set to `false`', async () => {
const mockError = { message: 'some error' };
mockEsClientInstance.ping.mockRejectedValue(mockError);
await expect(
clusterClient.callAsInternalUser('ping', undefined, { wrap401Errors: false })
).rejects.toBe(mockError);
const mockAuthenticationError = { message: 'authentication error', statusCode: 401 };
mockEsClientInstance.ping.mockRejectedValue(mockAuthenticationError);
await expect(
clusterClient.callAsInternalUser('ping', undefined, { wrap401Errors: false })
).rejects.toBe(mockAuthenticationError);
});
test('wraps 401 errors when `wrap401Errors` is set to `true` or unspecified', async () => {
const mockError = { message: 'some error' };
mockEsClientInstance.ping.mockRejectedValue(mockError);
await expect(clusterClient.callAsInternalUser('ping')).rejects.toBe(mockError);
await expect(
clusterClient.callAsInternalUser('ping', undefined, { wrap401Errors: true })
).rejects.toBe(mockError);
const mockAuthorizationError = { message: 'authentication error', statusCode: 403 };
mockEsClientInstance.ping.mockRejectedValue(mockAuthorizationError);
await expect(clusterClient.callAsInternalUser('ping')).rejects.toBe(mockAuthorizationError);
await expect(
clusterClient.callAsInternalUser('ping', undefined, { wrap401Errors: true })
).rejects.toBe(mockAuthorizationError);
const mockAuthenticationError = new (errors.AuthenticationException as any)(
'Authentication Exception',
{ statusCode: 401 }
);
mockEsClientInstance.ping.mockRejectedValue(mockAuthenticationError);
await expect(clusterClient.callAsInternalUser('ping')).rejects.toBe(mockAuthenticationError);
await expect(
clusterClient.callAsInternalUser('ping', undefined, { wrap401Errors: true })
).rejects.toStrictEqual(mockAuthenticationError);
});
test('aborts the request and rejects if a signal is provided and aborted', async () => {
const controller = new AbortController();
// The ES client returns a promise with an additional `abort` method to abort the request
const mockValue: any = Promise.resolve();
mockValue.abort = jest.fn();
mockEsClientInstance.ping.mockReturnValue(mockValue);
const promise = clusterClient.callAsInternalUser('ping', undefined, {
wrap401Errors: false,
signal: controller.signal,
});
controller.abort();
expect(mockValue.abort).toHaveBeenCalled();
await expect(promise).rejects.toThrowErrorMatchingInlineSnapshot(`"Request was aborted"`);
});
test('does not override WWW-Authenticate if returned by Elasticsearch', async () => {
const mockAuthenticationError = new (errors.AuthenticationException as any)(
'Authentication Exception',
{ statusCode: 401 }
);
const mockAuthenticationErrorWithHeader = new (errors.AuthenticationException as any)(
'Authentication Exception',
{
body: { error: { header: { 'WWW-Authenticate': 'some custom header' } } },
statusCode: 401,
}
);
mockEsClientInstance.ping
.mockRejectedValueOnce(mockAuthenticationError)
.mockRejectedValueOnce(mockAuthenticationErrorWithHeader);
await expect(clusterClient.callAsInternalUser('ping')).rejects.toBe(mockAuthenticationError);
expect(get(mockAuthenticationError, 'output.headers.WWW-Authenticate')).toBe(
'Basic realm="Authorization Required"'
);
await expect(clusterClient.callAsInternalUser('ping')).rejects.toBe(
mockAuthenticationErrorWithHeader
);
expect(get(mockAuthenticationErrorWithHeader, 'output.headers.WWW-Authenticate')).toBe(
'some custom header'
);
});
});
describe('#asScoped', () => {
let mockEsClientInstance: { ping: jest.Mock; close: jest.Mock };
let mockScopedEsClientInstance: { ping: jest.Mock; close: jest.Mock };
let clusterClient: LegacyClusterClient;
let mockLogger: Logger;
let mockEsConfig: ElasticsearchConfig;
beforeEach(() => {
mockEsClientInstance = { ping: jest.fn(), close: jest.fn() };
mockScopedEsClientInstance = { ping: jest.fn(), close: jest.fn() };
MockClient.mockImplementationOnce(() => mockEsClientInstance).mockImplementationOnce(
() => mockScopedEsClientInstance
);
mockLogger = logger.get();
mockEsConfig = {
apiVersion: 'es-version',
requestHeadersWhitelist: ['one', 'two'],
} as any;
clusterClient = new LegacyClusterClient(mockEsConfig, mockLogger, 'custom-type');
jest.clearAllMocks();
});
test('creates additional Elasticsearch client only once', () => {
const firstScopedClusterClient = clusterClient.asScoped(
httpServerMock.createRawRequest({ headers: { one: '1' } })
);
expect(firstScopedClusterClient).toBeDefined();
expect(mockParseElasticsearchClientConfig).toHaveBeenCalledTimes(1);
expect(mockParseElasticsearchClientConfig).toHaveBeenLastCalledWith(
mockEsConfig,
mockLogger,
'custom-type',
{
auth: false,
ignoreCertAndKey: true,
}
);
expect(MockClient).toHaveBeenCalledTimes(1);
expect(MockClient).toHaveBeenCalledWith(
mockParseElasticsearchClientConfig.mock.results[0].value
);
jest.clearAllMocks();
const secondScopedClusterClient = clusterClient.asScoped(
httpServerMock.createRawRequest({ headers: { two: '2' } })
);
expect(secondScopedClusterClient).toBeDefined();
expect(secondScopedClusterClient).not.toBe(firstScopedClusterClient);
expect(mockParseElasticsearchClientConfig).not.toHaveBeenCalled();
expect(MockClient).not.toHaveBeenCalled();
});
test('properly configures `ignoreCertAndKey` for various configurations', () => {
// Config without SSL.
clusterClient = new LegacyClusterClient(mockEsConfig, mockLogger, 'custom-type');
mockParseElasticsearchClientConfig.mockClear();
clusterClient.asScoped(httpServerMock.createRawRequest({ headers: { one: '1' } }));
expect(mockParseElasticsearchClientConfig).toHaveBeenCalledTimes(1);
expect(mockParseElasticsearchClientConfig).toHaveBeenLastCalledWith(
mockEsConfig,
mockLogger,
'custom-type',
{
auth: false,
ignoreCertAndKey: true,
}
);
// Config ssl.alwaysPresentCertificate === false
mockEsConfig = { ...mockEsConfig, ssl: { alwaysPresentCertificate: false } } as any;
clusterClient = new LegacyClusterClient(mockEsConfig, mockLogger, 'custom-type');
mockParseElasticsearchClientConfig.mockClear();
clusterClient.asScoped(httpServerMock.createRawRequest({ headers: { one: '1' } }));
expect(mockParseElasticsearchClientConfig).toHaveBeenCalledTimes(1);
expect(mockParseElasticsearchClientConfig).toHaveBeenLastCalledWith(
mockEsConfig,
mockLogger,
'custom-type',
{
auth: false,
ignoreCertAndKey: true,
}
);
// Config ssl.alwaysPresentCertificate === true
mockEsConfig = { ...mockEsConfig, ssl: { alwaysPresentCertificate: true } } as any;
clusterClient = new LegacyClusterClient(mockEsConfig, mockLogger, 'custom-type');
mockParseElasticsearchClientConfig.mockClear();
clusterClient.asScoped(httpServerMock.createRawRequest({ headers: { one: '1' } }));
expect(mockParseElasticsearchClientConfig).toHaveBeenCalledTimes(1);
expect(mockParseElasticsearchClientConfig).toHaveBeenLastCalledWith(
mockEsConfig,
mockLogger,
'custom-type',
{
auth: false,
ignoreCertAndKey: false,
}
);
});
test('passes only filtered headers to the scoped cluster client', () => {
clusterClient.asScoped(
httpServerMock.createRawRequest({ headers: { zero: '0', one: '1', two: '2', three: '3' } })
);
expect(MockScopedClusterClient).toHaveBeenCalledTimes(1);
expect(MockScopedClusterClient).toHaveBeenCalledWith(
expect.any(Function),
expect.any(Function),
{ one: '1', two: '2' }
);
});
test('passes x-opaque-id header with request id', () => {
clusterClient.asScoped(
httpServerMock.createKibanaRequest({
kibanaRequestState: { requestId: 'alpha', requestUuid: 'ignore-this-id' },
})
);
expect(MockScopedClusterClient).toHaveBeenCalledTimes(1);
expect(MockScopedClusterClient).toHaveBeenCalledWith(
expect.any(Function),
expect.any(Function),
{ 'x-opaque-id': 'alpha' }
);
});
test('does not set the authorization header when a service account token is configured', async () => {
clusterClient = new LegacyClusterClient(
{
apiVersion: 'es-version',
requestHeadersWhitelist: ['zero'],
serviceAccountToken: 'ABC123',
} as any,
logger.get(),
'custom-type'
);
clusterClient.asScoped(
httpServerMock.createRawRequest({ headers: { zero: '0', one: '1', two: '2', three: '3' } })
);
const expectedHeaders = { zero: '0' };
expect(MockScopedClusterClient).toHaveBeenCalledTimes(1);
expect(MockScopedClusterClient).toHaveBeenCalledWith(
expect.any(Function),
expect.any(Function),
expectedHeaders
);
});
test('both scoped and internal API caller fail if cluster client is closed', async () => {
clusterClient.asScoped(
httpServerMock.createRawRequest({ headers: { zero: '0', one: '1', two: '2', three: '3' } })
);
clusterClient.close();
const [[internalAPICaller, scopedAPICaller]] = MockScopedClusterClient.mock.calls;
await expect(internalAPICaller('ping')).rejects.toThrowErrorMatchingInlineSnapshot(
`"Cluster client cannot be used after it has been closed."`
);
await expect(scopedAPICaller('ping', {})).rejects.toThrowErrorMatchingInlineSnapshot(
`"Cluster client cannot be used after it has been closed."`
);
});
test('does not fail when scope to not defined request', async () => {
clusterClient = new LegacyClusterClient(mockEsConfig, mockLogger, 'custom-type');
clusterClient.asScoped();
expect(MockScopedClusterClient).toHaveBeenCalledTimes(1);
expect(MockScopedClusterClient).toHaveBeenCalledWith(
expect.any(Function),
expect.any(Function),
{}
);
});
test('does not fail when scope to a request without headers', async () => {
clusterClient = new LegacyClusterClient(mockEsConfig, mockLogger, 'custom-type');
clusterClient.asScoped({} as any);
expect(MockScopedClusterClient).toHaveBeenCalledTimes(1);
expect(MockScopedClusterClient).toHaveBeenCalledWith(
expect.any(Function),
expect.any(Function),
{}
);
});
test('calls getAuthHeaders and filters results for a real request', async () => {
clusterClient = new LegacyClusterClient(mockEsConfig, mockLogger, 'custom-type', () => ({
one: '1',
three: '3',
}));
clusterClient.asScoped(httpServerMock.createRawRequest({ headers: { two: '2' } }));
expect(MockScopedClusterClient).toHaveBeenCalledTimes(1);
expect(MockScopedClusterClient).toHaveBeenCalledWith(
expect.any(Function),
expect.any(Function),
{ one: '1', two: '2' }
);
});
test('getAuthHeaders results rewrite extends a request headers', async () => {
clusterClient = new LegacyClusterClient(mockEsConfig, mockLogger, 'custom-type', () => ({
one: 'foo',
}));
clusterClient.asScoped(httpServerMock.createRawRequest({ headers: { one: '1', two: '2' } }));
expect(MockScopedClusterClient).toHaveBeenCalledTimes(1);
expect(MockScopedClusterClient).toHaveBeenCalledWith(
expect.any(Function),
expect.any(Function),
{ one: 'foo', two: '2' }
);
});
test("doesn't call getAuthHeaders for a fake request", async () => {
clusterClient = new LegacyClusterClient(mockEsConfig, mockLogger, 'custom-type', () => ({}));
clusterClient.asScoped({ headers: { one: 'foo' } });
expect(MockScopedClusterClient).toHaveBeenCalledTimes(1);
expect(MockScopedClusterClient).toHaveBeenCalledWith(
expect.any(Function),
expect.any(Function),
{ one: 'foo' }
);
});
test('filters a fake request headers', async () => {
clusterClient = new LegacyClusterClient(mockEsConfig, mockLogger, 'custom-type');
clusterClient.asScoped({ headers: { one: '1', two: '2', three: '3' } });
expect(MockScopedClusterClient).toHaveBeenCalledTimes(1);
expect(MockScopedClusterClient).toHaveBeenCalledWith(
expect.any(Function),
expect.any(Function),
{ one: '1', two: '2' }
);
});
});
describe('#close', () => {
let mockEsClientInstance: { close: jest.Mock };
let mockScopedEsClientInstance: { close: jest.Mock };
let clusterClient: LegacyClusterClient;
beforeEach(() => {
mockEsClientInstance = { close: jest.fn() };
mockScopedEsClientInstance = { close: jest.fn() };
MockClient.mockImplementationOnce(() => mockEsClientInstance).mockImplementationOnce(
() => mockScopedEsClientInstance
);
clusterClient = new LegacyClusterClient(
{ apiVersion: 'es-version', requestHeadersWhitelist: [] } as any,
logger.get(),
'custom-type'
);
});
test('closes underlying Elasticsearch client', () => {
expect(mockEsClientInstance.close).not.toHaveBeenCalled();
clusterClient.close();
expect(mockEsClientInstance.close).toHaveBeenCalledTimes(1);
});
test('closes both internal and scoped underlying Elasticsearch clients', () => {
clusterClient.asScoped(httpServerMock.createRawRequest({ headers: { one: '1' } }));
expect(mockEsClientInstance.close).not.toHaveBeenCalled();
expect(mockScopedEsClientInstance.close).not.toHaveBeenCalled();
clusterClient.close();
expect(mockEsClientInstance.close).toHaveBeenCalledTimes(1);
expect(mockScopedEsClientInstance.close).toHaveBeenCalledTimes(1);
});
test('does not call close on already closed client', () => {
clusterClient.asScoped(httpServerMock.createRawRequest({ headers: { one: '1' } }));
clusterClient.close();
mockEsClientInstance.close.mockClear();
mockScopedEsClientInstance.close.mockClear();
clusterClient.close();
expect(mockEsClientInstance.close).not.toHaveBeenCalled();
expect(mockScopedEsClientInstance.close).not.toHaveBeenCalled();
});
});

View file

@ -1,256 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { Client } from 'elasticsearch';
import { get } from 'lodash';
import { LegacyElasticsearchErrorHelpers } from './errors';
import { GetAuthHeaders, isKibanaRequest, isRealRequest } from '../../http';
import { filterHeaders, ensureRawRequest } from '../../http/router';
import { Logger } from '../../logging';
import { ScopeableRequest } from '../types';
import {
LegacyElasticsearchClientConfig,
parseElasticsearchClientConfig,
} from './elasticsearch_client_config';
import { LegacyScopedClusterClient, ILegacyScopedClusterClient } from './scoped_cluster_client';
import { LegacyCallAPIOptions, LegacyAPICaller } from './api_types';
/**
* Support Legacy platform request for the period of migration.
*
* @public
*/
const noop = () => undefined;
/**
* Calls the Elasticsearch API endpoint with the specified parameters.
* @param client Raw Elasticsearch JS client instance to use.
* @param endpoint Name of the API endpoint to call.
* @param clientParams Parameters that will be directly passed to the
* Elasticsearch JS client.
* @param options Options that affect the way we call the API and process the result.
*/
const callAPI = async (
client: Client,
endpoint: string,
clientParams: Record<string, any> = {},
options: LegacyCallAPIOptions = { wrap401Errors: true }
) => {
const clientPath = endpoint.split('.');
const api: any = get(client, clientPath);
if (!api) {
throw new Error(`called with an invalid endpoint: ${endpoint}`);
}
const apiContext = clientPath.length === 1 ? client : get(client, clientPath.slice(0, -1));
try {
return await new Promise((resolve, reject) => {
const request = api.call(apiContext, clientParams);
if (options.signal) {
options.signal.addEventListener('abort', () => {
request.abort();
reject(new Error('Request was aborted'));
});
}
return request.then(resolve, reject);
});
} catch (err) {
if (!options.wrap401Errors || err.statusCode !== 401) {
throw err;
}
throw LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(err);
}
};
/**
* 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(...)`).
*
* See {@link LegacyClusterClient}.
*
* @deprecated Use {@link IClusterClient}.
* @removeBy 7.16
* @public
*/
export type ILegacyClusterClient = Pick<LegacyClusterClient, 'callAsInternalUser' | 'asScoped'>;
/**
* Represents an Elasticsearch cluster API client created by a plugin.
* 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(...)`).
*
* See {@link LegacyClusterClient}.
* @deprecated Use {@link ICustomClusterClient}.
* @removeBy 7.16
* @public
*/
export type ILegacyCustomClusterClient = Pick<
LegacyClusterClient,
'callAsInternalUser' | 'close' | 'asScoped'
>;
/**
* {@inheritDoc IClusterClient}
* @deprecated Use {@link IClusterClient}.
* @removeBy 7.16
* @public
*/
export class LegacyClusterClient implements ILegacyClusterClient {
/**
* Raw Elasticsearch JS client that acts on behalf of the Kibana internal user.
*/
private readonly client: Client;
/**
* Optional raw Elasticsearch JS client that is shared between all the scoped clients created
* from this cluster client. Every API call is attributed by the wh
*/
private scopedClient?: Client;
/**
* Indicates whether this cluster client (and all internal raw Elasticsearch JS clients) has been closed.
*/
private isClosed = false;
constructor(
private readonly config: LegacyElasticsearchClientConfig,
private readonly log: Logger,
private readonly type: string,
private readonly getAuthHeaders: GetAuthHeaders = noop
) {
this.client = new Client(parseElasticsearchClientConfig(config, log, type));
}
/**
* Calls specified endpoint with provided clientParams on behalf of the
* Kibana internal user.
* See {@link LegacyAPICaller}.
* @deprecated Use {@link IClusterClient.asInternalUser}.
*
* @param endpoint - String descriptor of the endpoint e.g. `cluster.getSettings` or `ping`.
* @param clientParams - A dictionary of parameters that will be passed directly to the Elasticsearch JS client.
* @param options - Options that affect the way we call the API and process the result.
*/
public callAsInternalUser: LegacyAPICaller = async (
endpoint: string,
clientParams: Record<string, any> = {},
options?: LegacyCallAPIOptions
) => {
this.assertIsNotClosed();
if (this.config.serviceAccountToken) {
clientParams.headers = {
...clientParams.headers,
authorization: `Bearer ${this.config.serviceAccountToken}`,
};
}
return await (callAPI.bind(null, this.client) as LegacyAPICaller)(
endpoint,
clientParams,
options
);
};
/**
* 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.client.close();
if (this.scopedClient !== undefined) {
this.scopedClient.close();
}
}
/**
* Creates an instance of {@link ILegacyScopedClusterClient} based on the configuration the
* current cluster client that exposes additional `callAsCurrentUser` method
* scoped to the provided req. Consumers shouldn't worry about closing
* scoped client instances, these will be automatically closed as soon as the
* original cluster client isn't needed anymore and closed.
*
* @param request - Request the `IScopedClusterClient` instance will be scoped to.
* Supports request optionality, Legacy.Request & FakeRequest for BWC with LegacyPlatform
*/
public asScoped(request?: ScopeableRequest): ILegacyScopedClusterClient {
// It'd have been quite expensive to create and configure client for every incoming
// request since it involves parsing of the config, reading of the SSL certificate and
// key files etc. Moreover scoped client needs two Elasticsearch JS clients at the same
// time: one to support `callAsInternalUser` and another one for `callAsCurrentUser`.
// To reduce that overhead we create one scoped client per cluster client and share it
// between all scoped client instances.
if (this.scopedClient === undefined) {
this.scopedClient = new Client(
parseElasticsearchClientConfig(this.config, this.log, this.type, {
auth: false,
ignoreCertAndKey: !this.config.ssl || !this.config.ssl.alwaysPresentCertificate,
})
);
}
return new LegacyScopedClusterClient(
this.callAsInternalUser,
this.callAsCurrentUser,
filterHeaders(this.getHeaders(request), [
'x-opaque-id',
...this.config.requestHeadersWhitelist,
])
);
}
/**
* Calls specified endpoint with provided clientParams on behalf of the
* user initiated request to the Kibana server (via HTTP request headers).
* See {@link LegacyAPICaller}.
*
* @param endpoint - String descriptor of the endpoint e.g. `cluster.getSettings` or `ping`.
* @param clientParams - A dictionary of parameters that will be passed directly to the Elasticsearch JS client.
* @param options - Options that affect the way we call the API and process the result.
*/
private callAsCurrentUser: LegacyAPICaller = async (
endpoint: string,
clientParams: Record<string, any> = {},
options?: LegacyCallAPIOptions
) => {
this.assertIsNotClosed();
return await (callAPI.bind(null, this.scopedClient!) as LegacyAPICaller)(
endpoint,
clientParams,
options
);
};
private assertIsNotClosed() {
if (this.isClosed) {
throw new Error('Cluster client cannot be used after it has been closed.');
}
}
private getHeaders(request?: ScopeableRequest): Record<string, string | string[] | undefined> {
if (!isRealRequest(request)) {
return request && request.headers ? request.headers : {};
}
const authHeaders = this.getAuthHeaders(request);
const requestHeaders = ensureRawRequest(request).headers;
const requestIdHeaders = isKibanaRequest(request) ? { 'x-opaque-id': request.id } : {};
return { ...requestHeaders, ...requestIdHeaders, ...authHeaders };
}
}

View file

@ -1,756 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { duration } from 'moment';
import { loggingSystemMock } from '../../logging/logging_system.mock';
import {
LegacyElasticsearchClientConfig,
parseElasticsearchClientConfig,
} from './elasticsearch_client_config';
import { DEFAULT_HEADERS } from '../default_headers';
const logger = loggingSystemMock.create();
afterEach(() => jest.clearAllMocks());
test('parses minimally specified config', () => {
expect(
parseElasticsearchClientConfig(
{
apiVersion: 'master',
customHeaders: { xsrf: 'something' },
sniffOnStart: false,
sniffOnConnectionFault: false,
hosts: ['http://localhost/elasticsearch'],
requestHeadersWhitelist: [],
},
logger.get(),
'custom-type'
)
).toMatchInlineSnapshot(`
Object {
"apiVersion": "master",
"hosts": Array [
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
"xsrf": "something",
},
"host": "localhost",
"path": "/elasticsearch",
"port": "80",
"protocol": "http:",
"query": null,
},
],
"keepAlive": true,
"log": [Function],
"sniffOnConnectionFault": false,
"sniffOnStart": false,
}
`);
});
test('parses fully specified config', () => {
const elasticsearchConfig: LegacyElasticsearchClientConfig = {
apiVersion: 'v7.0.0',
customHeaders: { xsrf: 'something' },
sniffOnStart: true,
sniffOnConnectionFault: true,
hosts: [
'http://localhost/elasticsearch',
'http://domain.com:1234/elasticsearch',
'https://es.local',
],
requestHeadersWhitelist: [],
username: 'elastic',
password: 'changeme',
pingTimeout: 12345,
requestTimeout: 54321,
sniffInterval: 11223344,
ssl: {
verificationMode: 'certificate',
certificateAuthorities: ['content-of-ca-path-1', 'content-of-ca-path-2'],
certificate: 'content-of-certificate-path',
key: 'content-of-key-path',
keyPassphrase: 'key-pass',
alwaysPresentCertificate: true,
},
};
const elasticsearchClientConfig = parseElasticsearchClientConfig(
elasticsearchConfig,
logger.get(),
'custom-type'
);
// Check that original references aren't used.
for (const host of elasticsearchClientConfig.hosts) {
expect(elasticsearchConfig.customHeaders).not.toBe(host.headers);
}
expect(elasticsearchConfig.ssl).not.toBe(elasticsearchClientConfig.ssl);
expect(elasticsearchClientConfig).toMatchInlineSnapshot(`
Object {
"apiVersion": "v7.0.0",
"hosts": Array [
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
"xsrf": "something",
},
"host": "localhost",
"path": "/elasticsearch",
"port": "80",
"protocol": "http:",
"query": null,
},
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
"xsrf": "something",
},
"host": "domain.com",
"path": "/elasticsearch",
"port": "1234",
"protocol": "http:",
"query": null,
},
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
"xsrf": "something",
},
"host": "es.local",
"path": "/",
"port": "443",
"protocol": "https:",
"query": null,
},
],
"httpAuth": "elastic:changeme",
"keepAlive": true,
"log": [Function],
"pingTimeout": 12345,
"requestTimeout": 54321,
"sniffInterval": 11223344,
"sniffOnConnectionFault": true,
"sniffOnStart": true,
"ssl": Object {
"ca": Array [
"content-of-ca-path-1",
"content-of-ca-path-2",
],
"cert": "content-of-certificate-path",
"checkServerIdentity": [Function],
"key": "content-of-key-path",
"passphrase": "key-pass",
"rejectUnauthorized": true,
},
}
`);
});
test('parses config timeouts of moment.Duration type', () => {
expect(
parseElasticsearchClientConfig(
{
apiVersion: 'master',
customHeaders: { xsrf: 'something' },
sniffOnStart: false,
sniffOnConnectionFault: false,
pingTimeout: duration(100, 'ms'),
requestTimeout: duration(30, 's'),
sniffInterval: duration(1, 'minute'),
hosts: ['http://localhost:9200/elasticsearch'],
requestHeadersWhitelist: [],
},
logger.get(),
'custom-type'
)
).toMatchInlineSnapshot(`
Object {
"apiVersion": "master",
"hosts": Array [
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
"xsrf": "something",
},
"host": "localhost",
"path": "/elasticsearch",
"port": "9200",
"protocol": "http:",
"query": null,
},
],
"keepAlive": true,
"log": [Function],
"pingTimeout": 100,
"requestTimeout": 30000,
"sniffInterval": 60000,
"sniffOnConnectionFault": false,
"sniffOnStart": false,
}
`);
});
describe('#auth', () => {
test('is not set if #auth = false even if username and password are provided', () => {
expect(
parseElasticsearchClientConfig(
{
apiVersion: 'v7.0.0',
customHeaders: { xsrf: 'something' },
sniffOnStart: true,
sniffOnConnectionFault: true,
hosts: ['http://user:password@localhost/elasticsearch', 'https://es.local'],
username: 'elastic',
password: 'changeme',
requestHeadersWhitelist: [],
},
logger.get(),
'custom-type',
{ auth: false }
)
).toMatchInlineSnapshot(`
Object {
"apiVersion": "v7.0.0",
"hosts": Array [
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
"xsrf": "something",
},
"host": "localhost",
"path": "/elasticsearch",
"port": "80",
"protocol": "http:",
"query": null,
},
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
"xsrf": "something",
},
"host": "es.local",
"path": "/",
"port": "443",
"protocol": "https:",
"query": null,
},
],
"keepAlive": true,
"log": [Function],
"sniffOnConnectionFault": true,
"sniffOnStart": true,
}
`);
});
test('is not set if username is not specified', () => {
expect(
parseElasticsearchClientConfig(
{
apiVersion: 'v7.0.0',
customHeaders: { xsrf: 'something' },
sniffOnStart: true,
sniffOnConnectionFault: true,
hosts: ['https://es.local'],
requestHeadersWhitelist: [],
password: 'changeme',
},
logger.get(),
'custom-type',
{ auth: true }
)
).toMatchInlineSnapshot(`
Object {
"apiVersion": "v7.0.0",
"hosts": Array [
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
"xsrf": "something",
},
"host": "es.local",
"path": "/",
"port": "443",
"protocol": "https:",
"query": null,
},
],
"keepAlive": true,
"log": [Function],
"sniffOnConnectionFault": true,
"sniffOnStart": true,
}
`);
});
test('is not set if password is not specified', () => {
expect(
parseElasticsearchClientConfig(
{
apiVersion: 'v7.0.0',
customHeaders: { xsrf: 'something' },
sniffOnStart: true,
sniffOnConnectionFault: true,
hosts: ['https://es.local'],
requestHeadersWhitelist: [],
username: 'elastic',
},
logger.get(),
'custom-type',
{ auth: true }
)
).toMatchInlineSnapshot(`
Object {
"apiVersion": "v7.0.0",
"hosts": Array [
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
"xsrf": "something",
},
"host": "es.local",
"path": "/",
"port": "443",
"protocol": "https:",
"query": null,
},
],
"keepAlive": true,
"log": [Function],
"sniffOnConnectionFault": true,
"sniffOnStart": true,
}
`);
});
});
describe('#serviceAccountToken', () => {
it('is set when #auth is true, and a token is provided', () => {
expect(
parseElasticsearchClientConfig(
{
apiVersion: 'v7.0.0',
customHeaders: { xsrf: 'something' },
sniffOnStart: true,
sniffOnConnectionFault: true,
hosts: ['https://es.local'],
requestHeadersWhitelist: [],
serviceAccountToken: 'ABC123',
},
logger.get(),
'custom-type',
{ auth: true }
)
).toMatchInlineSnapshot(`
Object {
"apiVersion": "v7.0.0",
"hosts": Array [
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
"xsrf": "something",
},
"host": "es.local",
"path": "/",
"port": "443",
"protocol": "https:",
"query": null,
},
],
"keepAlive": true,
"log": [Function],
"serviceAccountToken": "ABC123",
"sniffOnConnectionFault": true,
"sniffOnStart": true,
}
`);
});
it('is not set when #auth is true, and a token is not provided', () => {
expect(
parseElasticsearchClientConfig(
{
apiVersion: 'v7.0.0',
customHeaders: { xsrf: 'something' },
sniffOnStart: true,
sniffOnConnectionFault: true,
hosts: ['https://es.local'],
requestHeadersWhitelist: [],
},
logger.get(),
'custom-type',
{ auth: true }
)
).toMatchInlineSnapshot(`
Object {
"apiVersion": "v7.0.0",
"hosts": Array [
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
"xsrf": "something",
},
"host": "es.local",
"path": "/",
"port": "443",
"protocol": "https:",
"query": null,
},
],
"keepAlive": true,
"log": [Function],
"sniffOnConnectionFault": true,
"sniffOnStart": true,
}
`);
});
it('is not set when #auth is false, and a token is provided', () => {
expect(
parseElasticsearchClientConfig(
{
apiVersion: 'v7.0.0',
customHeaders: { xsrf: 'something' },
sniffOnStart: true,
sniffOnConnectionFault: true,
hosts: ['https://es.local'],
requestHeadersWhitelist: [],
serviceAccountToken: 'ABC123',
},
logger.get(),
'custom-type',
{ auth: false }
)
).toMatchInlineSnapshot(`
Object {
"apiVersion": "v7.0.0",
"hosts": Array [
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
"xsrf": "something",
},
"host": "es.local",
"path": "/",
"port": "443",
"protocol": "https:",
"query": null,
},
],
"keepAlive": true,
"log": [Function],
"sniffOnConnectionFault": true,
"sniffOnStart": true,
}
`);
});
});
describe('#customHeaders', () => {
test('override the default headers', () => {
const headerKey = Object.keys(DEFAULT_HEADERS)[0];
const parsedConfig = parseElasticsearchClientConfig(
{
apiVersion: 'master',
customHeaders: { [headerKey]: 'foo' },
sniffOnStart: false,
sniffOnConnectionFault: false,
hosts: ['http://localhost/elasticsearch'],
requestHeadersWhitelist: [],
},
logger.get(),
'custom-type'
);
expect(parsedConfig.hosts[0].headers).toEqual({
[headerKey]: 'foo',
});
});
});
describe('#log', () => {
test('default logger', () => {
const parsedConfig = parseElasticsearchClientConfig(
{
apiVersion: 'master',
customHeaders: { xsrf: 'something' },
sniffOnStart: false,
sniffOnConnectionFault: false,
hosts: ['http://localhost/elasticsearch'],
requestHeadersWhitelist: [],
},
logger.get(),
'custom-type'
);
const esLogger = new parsedConfig.log();
esLogger.error('some-error');
esLogger.warning('some-warning');
esLogger.trace('METHOD', { path: '/some-path' }, '?query=2', 'unknown', '304');
esLogger.info('some-info');
esLogger.debug('some-debug');
expect(typeof esLogger.close).toBe('function');
expect(loggingSystemMock.collect(logger)).toMatchInlineSnapshot(`
Object {
"debug": Array [
Array [
"304
METHOD /some-path
?query=2",
],
],
"error": Array [
Array [
"some-error",
],
],
"fatal": Array [],
"info": Array [],
"log": Array [],
"trace": Array [],
"warn": Array [
Array [
"some-warning",
],
],
}
`);
});
test('custom logger', () => {
const customLogger = jest.fn();
const parsedConfig = parseElasticsearchClientConfig(
{
apiVersion: 'master',
customHeaders: { xsrf: 'something' },
sniffOnStart: false,
sniffOnConnectionFault: false,
hosts: ['http://localhost/elasticsearch'],
requestHeadersWhitelist: [],
log: customLogger,
},
logger.get(),
'custom-type'
);
expect(parsedConfig.log).toBe(customLogger);
});
});
describe('#ssl', () => {
test('#verificationMode = none', () => {
expect(
parseElasticsearchClientConfig(
{
apiVersion: 'v7.0.0',
customHeaders: {},
sniffOnStart: true,
sniffOnConnectionFault: true,
hosts: ['https://es.local'],
requestHeadersWhitelist: [],
ssl: { verificationMode: 'none' },
},
logger.get(),
'custom-type'
)
).toMatchInlineSnapshot(`
Object {
"apiVersion": "v7.0.0",
"hosts": Array [
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
},
"host": "es.local",
"path": "/",
"port": "443",
"protocol": "https:",
"query": null,
},
],
"keepAlive": true,
"log": [Function],
"sniffOnConnectionFault": true,
"sniffOnStart": true,
"ssl": Object {
"ca": undefined,
"rejectUnauthorized": false,
},
}
`);
});
test('#verificationMode = certificate', () => {
const clientConfig = parseElasticsearchClientConfig(
{
apiVersion: 'v7.0.0',
customHeaders: {},
sniffOnStart: true,
sniffOnConnectionFault: true,
hosts: ['https://es.local'],
requestHeadersWhitelist: [],
ssl: { verificationMode: 'certificate' },
},
logger.get(),
'custom-type'
);
// `checkServerIdentity` shouldn't check hostname when verificationMode is certificate.
expect(
clientConfig.ssl!.checkServerIdentity!('right.com', { subject: { CN: 'wrong.com' } } as any)
).toBeUndefined();
expect(clientConfig).toMatchInlineSnapshot(`
Object {
"apiVersion": "v7.0.0",
"hosts": Array [
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
},
"host": "es.local",
"path": "/",
"port": "443",
"protocol": "https:",
"query": null,
},
],
"keepAlive": true,
"log": [Function],
"sniffOnConnectionFault": true,
"sniffOnStart": true,
"ssl": Object {
"ca": undefined,
"checkServerIdentity": [Function],
"rejectUnauthorized": true,
},
}
`);
});
test('#verificationMode = full', () => {
expect(
parseElasticsearchClientConfig(
{
apiVersion: 'v7.0.0',
customHeaders: {},
sniffOnStart: true,
sniffOnConnectionFault: true,
hosts: ['https://es.local'],
requestHeadersWhitelist: [],
ssl: { verificationMode: 'full' },
},
logger.get(),
'custom-type'
)
).toMatchInlineSnapshot(`
Object {
"apiVersion": "v7.0.0",
"hosts": Array [
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
},
"host": "es.local",
"path": "/",
"port": "443",
"protocol": "https:",
"query": null,
},
],
"keepAlive": true,
"log": [Function],
"sniffOnConnectionFault": true,
"sniffOnStart": true,
"ssl": Object {
"ca": undefined,
"rejectUnauthorized": true,
},
}
`);
});
test('#verificationMode is unknown', () => {
expect(() =>
parseElasticsearchClientConfig(
{
apiVersion: 'v7.0.0',
customHeaders: {},
sniffOnStart: true,
sniffOnConnectionFault: true,
hosts: ['https://es.local'],
requestHeadersWhitelist: [],
ssl: { verificationMode: 'misspelled' as any },
},
logger.get(),
'custom-type'
)
).toThrowErrorMatchingInlineSnapshot(`"Unknown ssl verificationMode: misspelled"`);
});
test('#ignoreCertAndKey = true', () => {
expect(
parseElasticsearchClientConfig(
{
apiVersion: 'v7.0.0',
customHeaders: {},
sniffOnStart: true,
sniffOnConnectionFault: true,
hosts: ['https://es.local'],
requestHeadersWhitelist: [],
ssl: {
verificationMode: 'certificate',
certificateAuthorities: ['content-of-ca-path'],
certificate: 'content-of-certificate-path',
key: 'content-of-key-path',
keyPassphrase: 'key-pass',
alwaysPresentCertificate: true,
},
},
logger.get(),
'custom-type',
{ ignoreCertAndKey: true }
)
).toMatchInlineSnapshot(`
Object {
"apiVersion": "v7.0.0",
"hosts": Array [
Object {
"headers": Object {
"x-elastic-product-origin": "kibana",
},
"host": "es.local",
"path": "/",
"port": "443",
"protocol": "https:",
"query": null,
},
],
"keepAlive": true,
"log": [Function],
"sniffOnConnectionFault": true,
"sniffOnStart": true,
"ssl": Object {
"ca": Array [
"content-of-ca-path",
],
"checkServerIdentity": [Function],
"rejectUnauthorized": true,
},
}
`);
});
});

View file

@ -1,224 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { ConfigOptions } from 'elasticsearch';
import { cloneDeep } from 'lodash';
import { Duration } from 'moment';
import { checkServerIdentity } from 'tls';
import url from 'url';
import { pick } from '@kbn/std';
import { Logger } from '../../logging';
import { ElasticsearchConfig } from '../elasticsearch_config';
import { DEFAULT_HEADERS } from '../default_headers';
/**
* @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).
*
* @deprecated
* @public
*/
export type LegacyElasticsearchClientConfig = Pick<ConfigOptions, 'keepAlive' | 'log' | 'plugins'> &
Pick<
ElasticsearchConfig,
| 'apiVersion'
| 'customHeaders'
| 'requestHeadersWhitelist'
| 'sniffOnStart'
| 'sniffOnConnectionFault'
| 'hosts'
| 'username'
| 'password'
| 'serviceAccountToken'
> & {
pingTimeout?: ElasticsearchConfig['pingTimeout'] | ConfigOptions['pingTimeout'];
requestTimeout?: ElasticsearchConfig['requestTimeout'] | ConfigOptions['requestTimeout'];
sniffInterval?: ElasticsearchConfig['sniffInterval'] | ConfigOptions['sniffInterval'];
ssl?: Partial<ElasticsearchConfig['ssl']>;
};
/** @internal */
interface LegacyElasticsearchClientConfigOverrides {
/**
* If set to `true`, username and password from the config won't be used
* to access Elasticsearch API even if these are specified.
*/
auth?: boolean;
/**
* If set to `true`, `ssl.key` and `ssl.certificate` provided through config won't
* be used to connect to Elasticsearch.
*/
ignoreCertAndKey?: boolean;
}
// Original `ConfigOptions` defines `ssl: object` so we need something more specific.
/** @internal */
type ExtendedConfigOptions = ConfigOptions &
Partial<{
serviceAccountToken?: string;
ssl: Partial<{
rejectUnauthorized: boolean;
checkServerIdentity: typeof checkServerIdentity;
ca: string[];
cert: string;
key: string;
passphrase: string;
}>;
}>;
/** @internal */
export function parseElasticsearchClientConfig(
config: LegacyElasticsearchClientConfig,
log: Logger,
type: string,
{ ignoreCertAndKey = false, auth = true }: LegacyElasticsearchClientConfigOverrides = {}
) {
const esClientConfig: ExtendedConfigOptions = {
keepAlive: true,
...pick(config, [
'apiVersion',
'sniffOnStart',
'sniffOnConnectionFault',
'keepAlive',
'log',
'plugins',
]),
};
if (esClientConfig.log == null) {
esClientConfig.log = getLoggerClass(log, type);
}
if (config.pingTimeout != null) {
esClientConfig.pingTimeout = getDurationAsMs(config.pingTimeout);
}
if (config.requestTimeout != null) {
esClientConfig.requestTimeout = getDurationAsMs(config.requestTimeout);
}
if (config.sniffInterval) {
esClientConfig.sniffInterval = getDurationAsMs(config.sniffInterval);
}
const needsAuth =
auth !== false && ((config.username && config.password) || config.serviceAccountToken);
if (needsAuth) {
if (config.username) {
esClientConfig.httpAuth = `${config.username}:${config.password}`;
} else if (config.serviceAccountToken) {
esClientConfig.serviceAccountToken = config.serviceAccountToken;
}
}
if (Array.isArray(config.hosts)) {
esClientConfig.hosts = config.hosts.map((nodeUrl: string) => {
const uri = url.parse(nodeUrl);
const httpsURI = uri.protocol === 'https:';
const httpURI = uri.protocol === 'http:';
const host: Record<string, unknown> = {
host: uri.hostname,
port: uri.port || (httpsURI && '443') || (httpURI && '80'),
protocol: uri.protocol,
path: uri.pathname,
query: uri.query,
headers: {
...DEFAULT_HEADERS,
...config.customHeaders,
},
};
return host;
});
}
if (config.ssl === undefined) {
return cloneDeep(esClientConfig);
}
esClientConfig.ssl = {};
const verificationMode = config.ssl.verificationMode;
switch (verificationMode) {
case 'none':
esClientConfig.ssl.rejectUnauthorized = false;
break;
case 'certificate':
esClientConfig.ssl.rejectUnauthorized = true;
// by default, NodeJS is checking the server identify
esClientConfig.ssl.checkServerIdentity = () => undefined;
break;
case 'full':
esClientConfig.ssl.rejectUnauthorized = true;
break;
default:
throw new Error(`Unknown ssl verificationMode: ${verificationMode}`);
}
esClientConfig.ssl.ca = config.ssl.certificateAuthorities;
// Add client certificate and key if required by elasticsearch
if (!ignoreCertAndKey && config.ssl.certificate && config.ssl.key) {
esClientConfig.ssl.cert = config.ssl.certificate;
esClientConfig.ssl.key = config.ssl.key;
esClientConfig.ssl.passphrase = config.ssl.keyPassphrase;
}
// Elasticsearch JS client mutates config object, so all properties that are
// usually passed by reference should be cloned to avoid any side effects.
return cloneDeep(esClientConfig);
}
function getDurationAsMs(duration: number | Duration) {
if (typeof duration === 'number') {
return duration;
}
return duration.asMilliseconds();
}
function getLoggerClass(log: Logger, type: string) {
const queryLogger = log.get('query', type);
return class ElasticsearchClientLogging {
public error(err: string | Error) {
log.error(err);
}
public warning(message: string) {
log.warn(message);
}
public trace(
method: string,
options: { path: string },
query: string,
_: unknown,
statusCode: string
) {
queryLogger.debug(`${statusCode}\n${method} ${options.path}\n${query ? query.trim() : ''}`);
}
// elasticsearch-js expects the following functions to exist
public info() {
// noop
}
public debug() {
// noop
}
public close() {
// noop
}
};
}

View file

@ -1,63 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import Boom from '@hapi/boom';
import { LegacyElasticsearchErrorHelpers } from './errors';
describe('ElasticsearchErrorHelpers', () => {
describe('NotAuthorized error', () => {
describe('decorateNotAuthorizedError', () => {
it('returns original object', () => {
const error = new Error();
expect(LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(error)).toBe(error);
});
it('makes the error identifiable as a NotAuthorized error', () => {
const error = new Error();
expect(LegacyElasticsearchErrorHelpers.isNotAuthorizedError(error)).toBe(false);
LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(error);
expect(LegacyElasticsearchErrorHelpers.isNotAuthorizedError(error)).toBe(true);
});
it('adds boom properties', () => {
const error = LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error());
expect(typeof error.output).toBe('object');
expect(error.output.statusCode).toBe(401);
});
it('preserves boom properties of input', () => {
const error = Boom.notFound();
LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(error);
expect(error.output.statusCode).toBe(404);
});
describe('error.output', () => {
it('defaults to message of error', () => {
const error = LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(
new Error('foobar')
);
expect(error.output.payload).toHaveProperty('message', 'foobar');
});
it('prefixes message with passed reason', () => {
const error = LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(
new Error('foobar'),
'biz'
);
expect(error.output.payload).toHaveProperty('message', 'biz: foobar');
});
it('sets statusCode to 401', () => {
const error = LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(
new Error('foo')
);
expect(error.output).toHaveProperty('statusCode', 401);
});
});
});
});
});

View file

@ -1,84 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import Boom from '@hapi/boom';
import { get } from 'lodash';
const code = Symbol('ElasticsearchError');
enum ErrorCode {
NOT_AUTHORIZED = 'Elasticsearch/notAuthorized',
}
/**
* @deprecated. The new elasticsearch client doesn't wrap errors anymore.
* @removeBy 7.16
* @public
* */
export interface LegacyElasticsearchError extends Boom.Boom {
[code]?: string;
}
function isElasticsearchError(error: any): error is LegacyElasticsearchError {
return Boolean(error && error[code]);
}
function decorate(
error: Error,
errorCode: ErrorCode,
statusCode: number,
message?: string
): LegacyElasticsearchError {
if (isElasticsearchError(error)) {
return error;
}
const boom = Boom.boomify(error, {
statusCode,
message,
// keep status and messages if Boom error object already has them
override: false,
}) as LegacyElasticsearchError;
boom[code] = errorCode;
return boom;
}
/**
* Helpers for working with errors returned from the Elasticsearch service.Since the internal data of
* errors are subject to change, consumers of the Elasticsearch service should always use these helpers
* to classify errors instead of checking error internals such as `body.error.header[WWW-Authenticate]`
* @public
*
* @example
* Handle errors
* ```js
* try {
* await client.asScoped(request).callAsCurrentUser(...);
* } catch (err) {
* if (ElasticsearchErrorHelpers.isNotAuthorizedError(err)) {
* const authHeader = err.output.headers['WWW-Authenticate'];
* }
* ```
*/
export class LegacyElasticsearchErrorHelpers {
public static isNotAuthorizedError(error: any): error is LegacyElasticsearchError {
return isElasticsearchError(error) && error[code] === ErrorCode.NOT_AUTHORIZED;
}
public static decorateNotAuthorizedError(error: Error, reason?: string) {
const decoratedError = decorate(error, ErrorCode.NOT_AUTHORIZED, 401, reason);
const wwwAuthHeader = get(error, 'body.error.header[WWW-Authenticate]') as string;
(decoratedError.output.headers as { [key: string]: string })['WWW-Authenticate'] =
wwwAuthHeader || 'Basic realm="Authorization Required"';
return decoratedError;
}
}

View file

@ -1,18 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
export { LegacyClusterClient } from './cluster_client';
export type { ILegacyClusterClient, ILegacyCustomClusterClient } from './cluster_client';
export type {
ILegacyScopedClusterClient,
LegacyScopedClusterClient,
} from './scoped_cluster_client';
export type { LegacyElasticsearchClientConfig } from './elasticsearch_client_config';
export { LegacyElasticsearchErrorHelpers } from './errors';
export type { LegacyElasticsearchError } from './errors';
export * from './api_types';

View file

@ -1,86 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { Client } from 'elasticsearch';
import { ILegacyScopedClusterClient } from './scoped_cluster_client';
import { ILegacyClusterClient, ILegacyCustomClusterClient } from './cluster_client';
const createScopedClusterClientMock = (): jest.Mocked<ILegacyScopedClusterClient> => ({
callAsInternalUser: jest.fn(),
callAsCurrentUser: jest.fn(),
});
const createCustomClusterClientMock = (): jest.Mocked<ILegacyCustomClusterClient> => ({
...createClusterClientMock(),
close: jest.fn(),
});
function createClusterClientMock() {
const client: jest.Mocked<ILegacyClusterClient> = {
callAsInternalUser: jest.fn(),
asScoped: jest.fn(),
};
client.asScoped.mockReturnValue(createScopedClusterClientMock());
return client;
}
const createElasticsearchClientMock = () => {
const mocked: jest.Mocked<Client> = {
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,
};

View file

@ -1,186 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { LegacyScopedClusterClient } from './scoped_cluster_client';
let internalAPICaller: jest.Mock;
let scopedAPICaller: jest.Mock;
let clusterClient: LegacyScopedClusterClient;
beforeEach(() => {
internalAPICaller = jest.fn();
scopedAPICaller = jest.fn();
clusterClient = new LegacyScopedClusterClient(internalAPICaller, scopedAPICaller, { one: '1' });
});
afterEach(() => jest.clearAllMocks());
describe('#callAsInternalUser', () => {
test('properly forwards arguments to the API caller and results back from it', async () => {
const mockResponse = { data: 'response' };
internalAPICaller.mockResolvedValue(mockResponse);
await expect(clusterClient.callAsInternalUser('ping')).resolves.toBe(mockResponse);
expect(internalAPICaller).toHaveBeenCalledTimes(1);
expect(internalAPICaller).toHaveBeenCalledWith('ping', {}, undefined);
internalAPICaller.mockClear();
await expect(
clusterClient.callAsInternalUser('security.authenticate', { some: 'some' })
).resolves.toBe(mockResponse);
expect(internalAPICaller).toHaveBeenCalledTimes(1);
expect(internalAPICaller).toHaveBeenCalledWith(
'security.authenticate',
{ some: 'some' },
undefined
);
internalAPICaller.mockClear();
await expect(
clusterClient.callAsInternalUser('ping', undefined, { wrap401Errors: true })
).resolves.toBe(mockResponse);
expect(internalAPICaller).toHaveBeenCalledTimes(1);
expect(internalAPICaller).toHaveBeenCalledWith('ping', {}, { wrap401Errors: true });
internalAPICaller.mockClear();
await expect(
clusterClient.callAsInternalUser(
'security.authenticate',
{ some: 'some' },
{ wrap401Errors: true }
)
).resolves.toBe(mockResponse);
expect(internalAPICaller).toHaveBeenCalledTimes(1);
expect(internalAPICaller).toHaveBeenCalledWith(
'security.authenticate',
{ some: 'some' },
{ wrap401Errors: true }
);
expect(scopedAPICaller).not.toHaveBeenCalled();
});
test('properly forwards errors returned by the API caller', async () => {
const mockErrorResponse = new Error('some-error');
internalAPICaller.mockRejectedValue(mockErrorResponse);
await expect(clusterClient.callAsInternalUser('ping')).rejects.toBe(mockErrorResponse);
expect(scopedAPICaller).not.toHaveBeenCalled();
});
});
describe('#callAsCurrentUser', () => {
test('properly forwards arguments to the API caller and results back from it', async () => {
const mockResponse = { data: 'response' };
scopedAPICaller.mockResolvedValue(mockResponse);
await expect(clusterClient.callAsCurrentUser('ping')).resolves.toBe(mockResponse);
expect(scopedAPICaller).toHaveBeenCalledTimes(1);
expect(scopedAPICaller).toHaveBeenCalledWith('ping', { headers: { one: '1' } }, undefined);
scopedAPICaller.mockClear();
await expect(
clusterClient.callAsCurrentUser('security.authenticate', { some: 'some' })
).resolves.toBe(mockResponse);
expect(scopedAPICaller).toHaveBeenCalledTimes(1);
expect(scopedAPICaller).toHaveBeenCalledWith(
'security.authenticate',
{ some: 'some', headers: { one: '1' } },
undefined
);
scopedAPICaller.mockClear();
await expect(
clusterClient.callAsCurrentUser('ping', undefined, { wrap401Errors: true })
).resolves.toBe(mockResponse);
expect(scopedAPICaller).toHaveBeenCalledTimes(1);
expect(scopedAPICaller).toHaveBeenCalledWith(
'ping',
{ headers: { one: '1' } },
{ wrap401Errors: true }
);
scopedAPICaller.mockClear();
await expect(
clusterClient.callAsCurrentUser(
'security.authenticate',
{ some: 'some', headers: { one: '1' } },
{ wrap401Errors: true }
)
).resolves.toBe(mockResponse);
expect(scopedAPICaller).toHaveBeenCalledTimes(1);
expect(scopedAPICaller).toHaveBeenCalledWith(
'security.authenticate',
{ some: 'some', headers: { one: '1' } },
{ wrap401Errors: true }
);
expect(internalAPICaller).not.toHaveBeenCalled();
});
test('callAsCurrentUser allows passing additional headers', async () => {
const mockResponse = { data: 'response' };
scopedAPICaller.mockResolvedValue(mockResponse);
await expect(
clusterClient.callAsCurrentUser('security.authenticate', {
some: 'some',
headers: { additionalHeader: 'Oh Yes!' },
})
).resolves.toBe(mockResponse);
expect(scopedAPICaller).toHaveBeenCalledTimes(1);
expect(scopedAPICaller).toHaveBeenCalledWith(
'security.authenticate',
{ some: 'some', headers: { one: '1', additionalHeader: 'Oh Yes!' } },
undefined
);
});
test('callAsCurrentUser cannot override default headers', async () => {
const expectedErrorResponse = new Error('Cannot override default header one.');
const withHeaderOverride = async () =>
clusterClient.callAsCurrentUser('security.authenticate', { headers: { one: 'OVERRIDE' } });
await expect(withHeaderOverride()).rejects.toThrowError(expectedErrorResponse);
expect(scopedAPICaller).toHaveBeenCalledTimes(0);
});
test('properly forwards errors returned by the API caller', async () => {
const mockErrorResponse = new Error('some-error');
scopedAPICaller.mockRejectedValue(mockErrorResponse);
await expect(clusterClient.callAsCurrentUser('ping')).rejects.toBe(mockErrorResponse);
expect(internalAPICaller).not.toHaveBeenCalled();
});
test('does not attach headers to the client params if they are not available', async () => {
const mockResponse = { data: 'response' };
scopedAPICaller.mockResolvedValue(mockResponse);
const clusterClientWithoutHeaders = new LegacyScopedClusterClient(
internalAPICaller,
scopedAPICaller
);
await expect(clusterClientWithoutHeaders.callAsCurrentUser('ping')).resolves.toBe(mockResponse);
expect(scopedAPICaller).toHaveBeenCalledTimes(1);
expect(scopedAPICaller).toHaveBeenCalledWith('ping', {}, undefined);
scopedAPICaller.mockClear();
await expect(
clusterClientWithoutHeaders.callAsCurrentUser('security.authenticate', { some: 'some' })
).resolves.toBe(mockResponse);
expect(scopedAPICaller).toHaveBeenCalledTimes(1);
expect(scopedAPICaller).toHaveBeenCalledWith(
'security.authenticate',
{ some: 'some' },
undefined
);
expect(internalAPICaller).not.toHaveBeenCalled();
});
});

View file

@ -1,98 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { intersection, isObject } from 'lodash';
import { Headers } from '../../http/router';
import { LegacyAPICaller, LegacyCallAPIOptions } from './api_types';
/**
* Serves the same purpose as "normal" `ClusterClient` but exposes additional
* `callAsCurrentUser` method that doesn't use credentials of the Kibana internal
* user (as `callAsInternalUser` does) to request Elasticsearch API, but rather
* passes HTTP headers extracted from the current user request to the API.
*
* See {@link LegacyScopedClusterClient}.
*
* @deprecated Use {@link IScopedClusterClient}.
* @removeBy 7.16
* @public
*/
export type ILegacyScopedClusterClient = Pick<
LegacyScopedClusterClient,
'callAsCurrentUser' | 'callAsInternalUser'
>;
/**
* {@inheritDoc IScopedClusterClient}
* @deprecated Use {@link IScopedClusterClient | scoped cluster client}.
* @removeBy 7.16
* @public
*/
export class LegacyScopedClusterClient implements ILegacyScopedClusterClient {
constructor(
private readonly internalAPICaller: LegacyAPICaller,
private readonly scopedAPICaller: LegacyAPICaller,
private readonly headers?: Headers
) {
this.callAsCurrentUser = this.callAsCurrentUser.bind(this);
this.callAsInternalUser = this.callAsInternalUser.bind(this);
}
/**
* Calls specified `endpoint` with provided `clientParams` on behalf of the
* Kibana internal user.
* See {@link LegacyAPICaller}.
* @deprecated Use {@link IScopedClusterClient.asInternalUser}.
* @removeBy 7.16
*
* @param endpoint - String descriptor of the endpoint e.g. `cluster.getSettings` or `ping`.
* @param clientParams - A dictionary of parameters that will be passed directly to the Elasticsearch JS client.
* @param options - Options that affect the way we call the API and process the result.
*/
public callAsInternalUser(
endpoint: string,
clientParams: Record<string, any> = {},
options?: LegacyCallAPIOptions
) {
return this.internalAPICaller(endpoint, clientParams, options);
}
/**
* Calls specified `endpoint` with provided `clientParams` on behalf of the
* user initiated request to the Kibana server (via HTTP request headers).
* See {@link LegacyAPICaller}.
* @deprecated Use {@link IScopedClusterClient.asCurrentUser}.
* @removeBy 7.16
*
* @param endpoint - String descriptor of the endpoint e.g. `cluster.getSettings` or `ping`.
* @param clientParams - A dictionary of parameters that will be passed directly to the Elasticsearch JS client.
* @param options - Options that affect the way we call the API and process the result.
*/
public callAsCurrentUser(
endpoint: string,
clientParams: Record<string, any> = {},
options?: LegacyCallAPIOptions
) {
const defaultHeaders = this.headers;
if (defaultHeaders !== undefined) {
const customHeaders: any = clientParams.headers;
if (isObject(customHeaders)) {
const duplicates = intersection(Object.keys(defaultHeaders), Object.keys(customHeaders));
duplicates.forEach((duplicate) => {
if (defaultHeaders[duplicate] !== (customHeaders as any)[duplicate]) {
throw Error(`Cannot override default header ${duplicate}.`);
}
});
}
clientParams.headers = Object.assign({}, clientParams.headers, this.headers);
}
return this.scopedAPICaller(endpoint, clientParams, options);
}
}

View file

@ -10,11 +10,6 @@ import { Observable } from 'rxjs';
import { Headers } from '../http/router';
import { LegacyRequest, KibanaRequest } from '../http';
import { ElasticsearchConfig } from './elasticsearch_config';
import {
LegacyElasticsearchClientConfig,
ILegacyClusterClient,
ILegacyCustomClusterClient,
} from './legacy';
import { IClusterClient, ICustomClusterClient, ElasticsearchClientConfig } from './client';
import { NodesVersionCompatibility } from './version_check/ensure_es_version';
import { ServiceStatus } from '../status';
@ -71,46 +66,6 @@ export interface ElasticsearchServiceSetup {
* @deprecated this will be removed in a later version.
*/
readonly config$: Observable<ElasticsearchConfig>;
/**
* @deprecated
* @removeBy 7.16
* Use {@link ElasticsearchServiceStart.legacy | ElasticsearchServiceStart.legacy.createClient} instead.
*
* Create application specific Elasticsearch cluster API client with customized config. See {@link ILegacyClusterClient}.
*
* @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.createCluster('my-app-name', config);
* const data = await client.callAsInternalUser();
* ```
*/
readonly createClient: (
type: string,
clientConfig?: Partial<LegacyElasticsearchClientConfig>
) => ILegacyCustomClusterClient;
/**
* @removeBy 7.16
* @deprecated
* Use {@link ElasticsearchServiceStart.legacy | ElasticsearchServiceStart.legacy.client} instead.
*
* All Elasticsearch config value changes are processed under the hood.
* See {@link ILegacyClusterClient}.
*
* @example
* ```js
* const client = core.elasticsearch.legacy.client;
* ```
*/
readonly client: ILegacyClusterClient;
};
}
@ -170,43 +125,6 @@ export interface ElasticsearchServiceStart {
* @deprecated this will be removed in a later version.
*/
readonly config$: Observable<ElasticsearchConfig>;
/**
* Create application specific Elasticsearch cluster API client with customized config. See {@link ILegacyClusterClient}.
*
* @deprecated
* @removeBy 7.16
*
* @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.legacy.createClient('my-app-name', config);
* const data = await client.callAsInternalUser();
* ```
*/
readonly createClient: (
type: string,
clientConfig?: Partial<LegacyElasticsearchClientConfig>
) => ILegacyCustomClusterClient;
/**
* A pre-configured {@link ILegacyClusterClient | legacy Elasticsearch client}.
*
* @deprecated
* @removeBy 7.16
*
* @example
* ```js
* const client = core.elasticsearch.legacy.client;
* ```
*/
readonly client: ILegacyClusterClient;
};
}

View file

@ -6,27 +6,6 @@
* Side Public License, v 1.
*/
import { elasticsearchServiceMock } from '../../elasticsearch/elasticsearch_service.mock';
export const MockLegacyScopedClusterClient = jest.fn();
export const legacyClusterClientInstanceMock = elasticsearchServiceMock.createLegacyScopedClusterClient();
jest.doMock('../../elasticsearch/legacy/scoped_cluster_client', () => ({
LegacyScopedClusterClient: MockLegacyScopedClusterClient.mockImplementation(
() => legacyClusterClientInstanceMock
),
}));
jest.doMock('elasticsearch', () => {
const realES = jest.requireActual('elasticsearch');
return {
...realES,
// eslint-disable-next-line object-shorthand
Client: function () {
return elasticsearchServiceMock.createLegacyElasticsearchClient();
},
};
});
export const MockElasticsearchClient = jest.fn();
jest.doMock('@elastic/elasticsearch', () => {
const real = jest.requireActual('@elastic/elasticsearch');

View file

@ -6,15 +6,7 @@
* Side Public License, v 1.
*/
import {
MockLegacyScopedClusterClient,
MockElasticsearchClient,
legacyClusterClientInstanceMock,
} from './core_service.test.mocks';
import { errors as esErrors } from 'elasticsearch';
import { LegacyElasticsearchErrorHelpers } from '../../elasticsearch/legacy';
import { MockElasticsearchClient } from './core_service.test.mocks';
import { elasticsearchClientMock } from '../../elasticsearch/client/mocks';
import { ResponseError } from '@elastic/elasticsearch/lib/errors';
import * as kbnTestServer from '../../../test_helpers/kbn_server';
@ -186,99 +178,6 @@ describe('http service', () => {
});
});
describe('legacy elasticsearch client', () => {
let root: ReturnType<typeof kbnTestServer.createRoot>;
beforeEach(async () => {
root = kbnTestServer.createRoot({ plugins: { initialize: false } });
await root.preboot();
}, 30000);
afterEach(async () => {
MockLegacyScopedClusterClient.mockClear();
await root.shutdown();
});
it('rewrites authorization header via authHeaders to make a request to Elasticsearch', async () => {
const authHeaders = { authorization: 'Basic: user:password' };
const { http } = await root.setup();
const { registerAuth, createRouter } = http;
registerAuth((req, res, toolkit) => toolkit.authenticated({ requestHeaders: authHeaders }));
const router = createRouter('/new-platform');
router.get({ path: '/', validate: false }, async (context, req, res) => {
// it forces client initialization since the core creates them lazily.
await context.core.elasticsearch.legacy.client.callAsCurrentUser('ping');
return res.ok();
});
await root.start();
await kbnTestServer.request.get(root, '/new-platform/').expect(200);
// client contains authHeaders for BWC with legacy platform.
const [client] = MockLegacyScopedClusterClient.mock.calls;
const [, , clientHeaders] = client;
expect(clientHeaders).toEqual({
...authHeaders,
'x-opaque-id': expect.any(String),
});
});
it('passes request authorization header to Elasticsearch if registerAuth was not set', async () => {
const authorizationHeader = 'Basic: username:password';
const { http } = await root.setup();
const { createRouter } = http;
const router = createRouter('/new-platform');
router.get({ path: '/', validate: false }, async (context, req, res) => {
// it forces client initialization since the core creates them lazily.
await context.core.elasticsearch.legacy.client.callAsCurrentUser('ping');
return res.ok();
});
await root.start();
await kbnTestServer.request
.get(root, '/new-platform/')
.set('Authorization', authorizationHeader)
.expect(200);
const [client] = MockLegacyScopedClusterClient.mock.calls;
const [, , clientHeaders] = client;
expect(clientHeaders).toEqual({
authorization: authorizationHeader,
'x-opaque-id': expect.any(String),
});
});
it('forwards 401 errors returned from elasticsearch', async () => {
const { http } = await root.setup();
const { createRouter } = http;
const authenticationError = LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(
new (esErrors.AuthenticationException as any)('Authentication Exception', {
body: { error: { header: { 'WWW-Authenticate': 'authenticate header' } } },
statusCode: 401,
})
);
legacyClusterClientInstanceMock.callAsCurrentUser.mockRejectedValue(authenticationError);
const router = createRouter('/new-platform');
router.get({ path: '/', validate: false }, async (context, req, res) => {
await context.core.elasticsearch.legacy.client.callAsCurrentUser('ping');
return res.ok();
});
await root.start();
const response = await kbnTestServer.request.get(root, '/new-platform/').expect(401);
expect(response.header['www-authenticate']).toEqual('authenticate header');
});
});
describe('elasticsearch client', () => {
let root: ReturnType<typeof kbnTestServer.createRoot>;

View file

@ -11,7 +11,6 @@ import Boom from '@hapi/boom';
import { isConfigSchema } from '@kbn/config-schema';
import { Logger } from '../../logging';
import { LegacyElasticsearchErrorHelpers } from '../../elasticsearch/legacy/errors';
import {
isUnauthorizedError as isElasticsearchUnauthorizedError,
UnauthorizedError as EsNotAuthorizedError,
@ -280,10 +279,6 @@ export class Router<Context extends RequestHandlerContext = RequestHandlerContex
kibanaResponseFactory.unauthorized(convertEsUnauthorized(e))
);
}
// forward 401 (boom) errors from legacy ES client
if (LegacyElasticsearchErrorHelpers.isNotAuthorizedError(e)) {
return e;
}
return hapiResponseAdapter.toInternalError();
}
}

View file

@ -31,7 +31,6 @@
import { Type } from '@kbn/config-schema';
import {
ElasticsearchServiceSetup,
ILegacyScopedClusterClient,
configSchema as elasticsearchConfigSchema,
ElasticsearchServiceStart,
IScopedClusterClient,
@ -117,20 +116,11 @@ export type { ICspConfig } from './csp';
export { ElasticsearchConfig } from './elasticsearch';
export type {
LegacyClusterClient,
ILegacyClusterClient,
ILegacyCustomClusterClient,
LegacyScopedClusterClient,
ILegacyScopedClusterClient,
LegacyElasticsearchClientConfig,
LegacyElasticsearchError,
LegacyElasticsearchErrorHelpers,
ElasticsearchServicePreboot,
ElasticsearchServiceSetup,
ElasticsearchServiceStart,
ElasticsearchStatusMeta,
NodesVersionCompatibility,
LegacyAPICaller,
FakeRequest,
ScopeableRequest,
ElasticsearchClient,
@ -147,17 +137,6 @@ export type {
ElasticsearchConfigPreboot,
} from './elasticsearch';
export type {
LegacyCallAPIOptions,
AssistantAPIClientParams,
MIGRATION_ASSISTANCE_INDEX_ACTION,
MIGRATION_DEPRECATION_LEVEL,
AssistanceAPIResponse,
DeprecationAPIClientParams,
DeprecationInfo,
IndexSettingsDeprecationInfo,
DeprecationAPIResponse,
} from './elasticsearch/legacy/api_types';
export type { IExternalUrlConfig, IExternalUrlPolicy } from './external_url';
export type {
AuthenticationHandler,
@ -462,12 +441,6 @@ export interface RequestHandlerContext {
};
elasticsearch: {
client: IScopedClusterClient;
legacy: {
/*
* @deprecated Use {@link IScopedClusterClient}.
*/
client: ILegacyScopedClusterClient;
};
};
uiSettings: {
client: IUiSettingsClient;

View file

@ -252,9 +252,6 @@ function createCoreRequestHandlerContextMock() {
},
elasticsearch: {
client: elasticsearchServiceMock.createScopedClusterClient(),
legacy: {
client: elasticsearchServiceMock.createLegacyScopedClusterClient(),
},
},
uiSettings: {
client: uiSettingsServiceMock.createClient(),

View file

@ -7,45 +7,14 @@
import { AddConfigDeprecation } from '@kbn/config';
import { ApiResponse } from '@elastic/elasticsearch/lib/Transport';
import Boom from '@hapi/boom';
import { BulkIndexDocumentsParams } from 'elasticsearch';
import { ByteSizeValue } from '@kbn/config-schema';
import { CatAliasesParams } from 'elasticsearch';
import { CatAllocationParams } from 'elasticsearch';
import { CatCommonParams } from 'elasticsearch';
import { CatFielddataParams } from 'elasticsearch';
import { CatHealthParams } from 'elasticsearch';
import { CatHelpParams } from 'elasticsearch';
import { CatIndicesParams } from 'elasticsearch';
import { CatRecoveryParams } from 'elasticsearch';
import { CatSegmentsParams } from 'elasticsearch';
import { CatShardsParams } from 'elasticsearch';
import { CatSnapshotsParams } from 'elasticsearch';
import { CatTasksParams } from 'elasticsearch';
import { CatThreadPoolParams } from 'elasticsearch';
import { ClearScrollParams } from 'elasticsearch';
import { CliArgs } from '@kbn/config';
import { Client } from 'elasticsearch';
import { ClientOptions } from '@elastic/elasticsearch';
import { ClusterAllocationExplainParams } from 'elasticsearch';
import { ClusterGetSettingsParams } from 'elasticsearch';
import { ClusterHealthParams } from 'elasticsearch';
import { ClusterPendingTasksParams } from 'elasticsearch';
import { ClusterPutSettingsParams } from 'elasticsearch';
import { ClusterRerouteParams } from 'elasticsearch';
import { ClusterStateParams } from 'elasticsearch';
import { ClusterStatsParams } from 'elasticsearch';
import { ConfigDeprecation } from '@kbn/config';
import { ConfigDeprecationFactory } from '@kbn/config';
import { ConfigDeprecationProvider } from '@kbn/config';
import { ConfigOptions } from 'elasticsearch';
import { ConfigPath } from '@kbn/config';
import { ConfigService } from '@kbn/config';
import { CountParams } from 'elasticsearch';
import { CreateDocumentParams } from 'elasticsearch';
import { DeleteDocumentByQueryParams } from 'elasticsearch';
import { DeleteDocumentParams } from 'elasticsearch';
import { DeleteScriptParams } from 'elasticsearch';
import { DeleteTemplateParams } from 'elasticsearch';
import { DetailedPeerCertificate } from 'tls';
import { Duration } from 'moment';
import { Duration as Duration_2 } from 'moment-timezone';
@ -56,121 +25,34 @@ import { EcsEventOutcome } from '@kbn/logging';
import { EcsEventType } from '@kbn/logging';
import { EnvironmentMode } from '@kbn/config';
import { estypes } from '@elastic/elasticsearch';
import { ExistsParams } from 'elasticsearch';
import { ExplainParams } from 'elasticsearch';
import { FieldStatsParams } from 'elasticsearch';
import { GenericParams } from 'elasticsearch';
import { GetParams } from 'elasticsearch';
import { GetResponse as GetResponse_2 } from 'elasticsearch';
import { GetScriptParams } from 'elasticsearch';
import { GetSourceParams } from 'elasticsearch';
import { GetTemplateParams } from 'elasticsearch';
import { IncomingHttpHeaders } from 'http';
import { IndexDocumentParams } from 'elasticsearch';
import { IndicesAnalyzeParams } from 'elasticsearch';
import { IndicesClearCacheParams } from 'elasticsearch';
import { IndicesCloseParams } from 'elasticsearch';
import { IndicesCreateParams } from 'elasticsearch';
import { IndicesDeleteAliasParams } from 'elasticsearch';
import { IndicesDeleteParams } from 'elasticsearch';
import { IndicesDeleteTemplateParams } from 'elasticsearch';
import { IndicesExistsAliasParams } from 'elasticsearch';
import { IndicesExistsParams } from 'elasticsearch';
import { IndicesExistsTemplateParams } from 'elasticsearch';
import { IndicesExistsTypeParams } from 'elasticsearch';
import { IndicesFlushParams } from 'elasticsearch';
import { IndicesFlushSyncedParams } from 'elasticsearch';
import { IndicesForcemergeParams } from 'elasticsearch';
import { IndicesGetAliasParams } from 'elasticsearch';
import { IndicesGetFieldMappingParams } from 'elasticsearch';
import { IndicesGetMappingParams } from 'elasticsearch';
import { IndicesGetParams } from 'elasticsearch';
import { IndicesGetSettingsParams } from 'elasticsearch';
import { IndicesGetTemplateParams } from 'elasticsearch';
import { IndicesGetUpgradeParams } from 'elasticsearch';
import { IndicesOpenParams } from 'elasticsearch';
import { IndicesPutAliasParams } from 'elasticsearch';
import { IndicesPutMappingParams } from 'elasticsearch';
import { IndicesPutSettingsParams } from 'elasticsearch';
import { IndicesPutTemplateParams } from 'elasticsearch';
import { IndicesRecoveryParams } from 'elasticsearch';
import { IndicesRefreshParams } from 'elasticsearch';
import { IndicesRolloverParams } from 'elasticsearch';
import { IndicesSegmentsParams } from 'elasticsearch';
import { IndicesShardStoresParams } from 'elasticsearch';
import { IndicesShrinkParams } from 'elasticsearch';
import { IndicesStatsParams } from 'elasticsearch';
import { IndicesUpdateAliasesParams } from 'elasticsearch';
import { IndicesUpgradeParams } from 'elasticsearch';
import { IndicesValidateQueryParams } from 'elasticsearch';
import { InfoParams } from 'elasticsearch';
import { IngestDeletePipelineParams } from 'elasticsearch';
import { IngestGetPipelineParams } from 'elasticsearch';
import { IngestPutPipelineParams } from 'elasticsearch';
import { IngestSimulateParams } from 'elasticsearch';
import { KibanaClient } from '@elastic/elasticsearch/api/kibana';
import { Logger } from '@kbn/logging';
import { LoggerFactory } from '@kbn/logging';
import { LogLevel } from '@kbn/logging';
import { LogMeta } from '@kbn/logging';
import { LogRecord } from '@kbn/logging';
import { MGetParams } from 'elasticsearch';
import { MGetResponse } from 'elasticsearch';
import { MSearchParams } from 'elasticsearch';
import { MSearchResponse } from 'elasticsearch';
import { MSearchTemplateParams } from 'elasticsearch';
import { MTermVectorsParams } from 'elasticsearch';
import { NodesHotThreadsParams } from 'elasticsearch';
import { NodesInfoParams } from 'elasticsearch';
import { NodesStatsParams } from 'elasticsearch';
import { ObjectType } from '@kbn/config-schema';
import { Observable } from 'rxjs';
import { PackageInfo } from '@kbn/config';
import { PathConfigType } from '@kbn/utils';
import { PeerCertificate } from 'tls';
import { PingParams } from 'elasticsearch';
import { PublicMethodsOf } from '@kbn/utility-types';
import { PutScriptParams } from 'elasticsearch';
import { PutTemplateParams } from 'elasticsearch';
import { Readable } from 'stream';
import { RecursiveReadonly } from '@kbn/utility-types';
import { ReindexParams } from 'elasticsearch';
import { ReindexRethrottleParams } from 'elasticsearch';
import { RenderSearchTemplateParams } from 'elasticsearch';
import { Request } from '@hapi/hapi';
import { RequestHandlerContext as RequestHandlerContext_2 } from 'src/core/server';
import { ResponseObject } from '@hapi/hapi';
import { ResponseToolkit } from '@hapi/hapi';
import { SchemaTypeError } from '@kbn/config-schema';
import { ScrollParams } from 'elasticsearch';
import { SearchParams } from 'elasticsearch';
import { SearchResponse as SearchResponse_2 } from 'elasticsearch';
import { SearchShardsParams } from 'elasticsearch';
import { SearchTemplateParams } from 'elasticsearch';
import { ShallowPromise } from '@kbn/utility-types';
import { SnapshotCreateParams } from 'elasticsearch';
import { SnapshotCreateRepositoryParams } from 'elasticsearch';
import { SnapshotDeleteParams } from 'elasticsearch';
import { SnapshotDeleteRepositoryParams } from 'elasticsearch';
import { SnapshotGetParams } from 'elasticsearch';
import { SnapshotGetRepositoryParams } from 'elasticsearch';
import { SnapshotRestoreParams } from 'elasticsearch';
import { SnapshotStatusParams } from 'elasticsearch';
import { SnapshotVerifyRepositoryParams } from 'elasticsearch';
import { Stream } from 'stream';
import { SuggestParams } from 'elasticsearch';
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 { UiCounterMetricType } from '@kbn/analytics';
import { UpdateDocumentByQueryParams } from 'elasticsearch';
import { UpdateDocumentParams } from 'elasticsearch';
import { URL } from 'url';
export { AddConfigDeprecation }
@ -196,24 +78,6 @@ export interface AppCategory {
// @public (undocumented)
export type AppenderConfigType = ConsoleAppenderConfig | FileAppenderConfig | LegacyAppenderConfig | RewriteAppenderConfig | RollingFileAppenderConfig;
// @public @deprecated (undocumented)
export interface AssistanceAPIResponse {
// (undocumented)
indices: {
[indexName: string]: {
action_required: MIGRATION_ASSISTANCE_INDEX_ACTION;
};
};
}
// @public @deprecated (undocumented)
export interface AssistantAPIClientParams extends GenericParams {
// (undocumented)
method: 'GET';
// (undocumented)
path: '/_migration/assistance';
}
// @public @deprecated
export interface AsyncPlugin<TSetup = void, TStart = void, TPluginsSetup extends object = object, TPluginsStart extends object = object> {
// (undocumented)
@ -862,38 +726,6 @@ export interface DeleteDocumentResponse {
_version: number;
}
// @public @deprecated (undocumented)
export interface DeprecationAPIClientParams extends GenericParams {
// (undocumented)
method: 'GET';
// (undocumented)
path: '/_migration/deprecations';
}
// @public @deprecated (undocumented)
export interface DeprecationAPIResponse {
// (undocumented)
cluster_settings: DeprecationInfo[];
// (undocumented)
index_settings: IndexSettingsDeprecationInfo;
// (undocumented)
ml_settings: DeprecationInfo[];
// (undocumented)
node_settings: DeprecationInfo[];
}
// @public @deprecated (undocumented)
export interface DeprecationInfo {
// (undocumented)
details?: string;
// (undocumented)
level: MIGRATION_DEPRECATION_LEVEL;
// (undocumented)
message: string;
// (undocumented)
url: string;
}
// @public
export interface DeprecationsClient {
// Warning: (ae-forgotten-export) The symbol "DomainDeprecationDetails" needs to be exported by the entry point index.d.ts
@ -1019,8 +851,6 @@ export interface ElasticsearchServiceSetup {
// @deprecated (undocumented)
legacy: {
readonly config$: Observable<ElasticsearchConfig>;
readonly createClient: (type: string, clientConfig?: Partial<LegacyElasticsearchClientConfig>) => ILegacyCustomClusterClient;
readonly client: ILegacyClusterClient;
};
}
@ -1031,8 +861,6 @@ export interface ElasticsearchServiceStart {
// @deprecated (undocumented)
legacy: {
readonly config$: Observable<ElasticsearchConfig>;
readonly createClient: (type: string, clientConfig?: Partial<LegacyElasticsearchClientConfig>) => ILegacyCustomClusterClient;
readonly client: ILegacyClusterClient;
};
}
@ -1286,21 +1114,6 @@ export interface IKibanaSocket {
}): Promise<void>;
}
// @public @deprecated
export type ILegacyClusterClient = Pick<LegacyClusterClient, 'callAsInternalUser' | 'asScoped'>;
// @public @deprecated
export type ILegacyCustomClusterClient = Pick<LegacyClusterClient, 'callAsInternalUser' | 'close' | 'asScoped'>;
// @public @deprecated
export type ILegacyScopedClusterClient = Pick<LegacyScopedClusterClient, 'callAsCurrentUser' | 'callAsInternalUser'>;
// @public @deprecated (undocumented)
export interface IndexSettingsDeprecationInfo {
// (undocumented)
[indexName: string]: DeprecationInfo[];
}
// @public (undocumented)
export interface IRenderOptions {
includeUserSettings?: boolean;
@ -1450,300 +1263,10 @@ export const kibanaResponseFactory: {
// @public
export type KnownHeaders = KnownKeys<IncomingHttpHeaders>;
// @public @deprecated (undocumented)
export interface LegacyAPICaller {
// (undocumented)
(endpoint: 'bulk', params: BulkIndexDocumentsParams, options?: LegacyCallAPIOptions): ReturnType<Client['bulk']>;
// (undocumented)
(endpoint: 'clearScroll', params: ClearScrollParams, options?: LegacyCallAPIOptions): ReturnType<Client['clearScroll']>;
// (undocumented)
(endpoint: 'count', params: CountParams, options?: LegacyCallAPIOptions): ReturnType<Client['count']>;
// (undocumented)
(endpoint: 'create', params: CreateDocumentParams, options?: LegacyCallAPIOptions): ReturnType<Client['create']>;
// (undocumented)
(endpoint: 'delete', params: DeleteDocumentParams, options?: LegacyCallAPIOptions): ReturnType<Client['delete']>;
// (undocumented)
(endpoint: 'deleteByQuery', params: DeleteDocumentByQueryParams, options?: LegacyCallAPIOptions): ReturnType<Client['deleteByQuery']>;
// (undocumented)
(endpoint: 'deleteScript', params: DeleteScriptParams, options?: LegacyCallAPIOptions): ReturnType<Client['deleteScript']>;
// (undocumented)
(endpoint: 'deleteTemplate', params: DeleteTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['deleteTemplate']>;
// (undocumented)
(endpoint: 'exists', params: ExistsParams, options?: LegacyCallAPIOptions): ReturnType<Client['exists']>;
// (undocumented)
(endpoint: 'explain', params: ExplainParams, options?: LegacyCallAPIOptions): ReturnType<Client['explain']>;
// (undocumented)
(endpoint: 'fieldStats', params: FieldStatsParams, options?: LegacyCallAPIOptions): ReturnType<Client['fieldStats']>;
// (undocumented)
<T>(endpoint: 'get', params: GetParams, options?: LegacyCallAPIOptions): Promise<GetResponse_2<T>>;
// (undocumented)
(endpoint: 'getScript', params: GetScriptParams, options?: LegacyCallAPIOptions): ReturnType<Client['getScript']>;
// (undocumented)
(endpoint: 'getSource', params: GetSourceParams, options?: LegacyCallAPIOptions): ReturnType<Client['getSource']>;
// (undocumented)
(endpoint: 'getTemplate', params: GetTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['getTemplate']>;
// (undocumented)
<T>(endpoint: 'index', params: IndexDocumentParams<T>, options?: LegacyCallAPIOptions): ReturnType<Client['index']>;
// (undocumented)
(endpoint: 'info', params: InfoParams, options?: LegacyCallAPIOptions): ReturnType<Client['info']>;
// (undocumented)
<T>(endpoint: 'mget', params: MGetParams, options?: LegacyCallAPIOptions): Promise<MGetResponse<T>>;
// (undocumented)
<T>(endpoint: 'msearch', params: MSearchParams, options?: LegacyCallAPIOptions): Promise<MSearchResponse<T>>;
// (undocumented)
<T>(endpoint: 'msearchTemplate', params: MSearchTemplateParams, options?: LegacyCallAPIOptions): Promise<MSearchResponse<T>>;
// (undocumented)
(endpoint: 'mtermvectors', params: MTermVectorsParams, options?: LegacyCallAPIOptions): ReturnType<Client['mtermvectors']>;
// (undocumented)
(endpoint: 'ping', params: PingParams, options?: LegacyCallAPIOptions): ReturnType<Client['ping']>;
// (undocumented)
(endpoint: 'putScript', params: PutScriptParams, options?: LegacyCallAPIOptions): ReturnType<Client['putScript']>;
// (undocumented)
(endpoint: 'putTemplate', params: PutTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['putTemplate']>;
// (undocumented)
(endpoint: 'reindex', params: ReindexParams, options?: LegacyCallAPIOptions): ReturnType<Client['reindex']>;
// (undocumented)
(endpoint: 'reindexRethrottle', params: ReindexRethrottleParams, options?: LegacyCallAPIOptions): ReturnType<Client['reindexRethrottle']>;
// (undocumented)
(endpoint: 'renderSearchTemplate', params: RenderSearchTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['renderSearchTemplate']>;
// (undocumented)
<T>(endpoint: 'scroll', params: ScrollParams, options?: LegacyCallAPIOptions): Promise<SearchResponse_2<T>>;
// (undocumented)
<T>(endpoint: 'search', params: SearchParams, options?: LegacyCallAPIOptions): Promise<SearchResponse_2<T>>;
// (undocumented)
(endpoint: 'searchShards', params: SearchShardsParams, options?: LegacyCallAPIOptions): ReturnType<Client['searchShards']>;
// (undocumented)
(endpoint: 'searchTemplate', params: SearchTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['searchTemplate']>;
// (undocumented)
(endpoint: 'suggest', params: SuggestParams, options?: LegacyCallAPIOptions): ReturnType<Client['suggest']>;
// (undocumented)
(endpoint: 'termvectors', params: TermvectorsParams, options?: LegacyCallAPIOptions): ReturnType<Client['termvectors']>;
// (undocumented)
(endpoint: 'update', params: UpdateDocumentParams, options?: LegacyCallAPIOptions): ReturnType<Client['update']>;
// (undocumented)
(endpoint: 'updateByQuery', params: UpdateDocumentByQueryParams, options?: LegacyCallAPIOptions): ReturnType<Client['updateByQuery']>;
// (undocumented)
(endpoint: 'cat.aliases', params: CatAliasesParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['aliases']>;
// (undocumented)
(endpoint: 'cat.allocation', params: CatAllocationParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['allocation']>;
// (undocumented)
(endpoint: 'cat.count', params: CatAllocationParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['count']>;
// (undocumented)
(endpoint: 'cat.fielddata', params: CatFielddataParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['fielddata']>;
// (undocumented)
(endpoint: 'cat.health', params: CatHealthParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['health']>;
// (undocumented)
(endpoint: 'cat.help', params: CatHelpParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['help']>;
// (undocumented)
(endpoint: 'cat.indices', params: CatIndicesParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['indices']>;
// (undocumented)
(endpoint: 'cat.master', params: CatCommonParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['master']>;
// (undocumented)
(endpoint: 'cat.nodeattrs', params: CatCommonParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['nodeattrs']>;
// (undocumented)
(endpoint: 'cat.nodes', params: CatCommonParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['nodes']>;
// (undocumented)
(endpoint: 'cat.pendingTasks', params: CatCommonParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['pendingTasks']>;
// (undocumented)
(endpoint: 'cat.plugins', params: CatCommonParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['plugins']>;
// (undocumented)
(endpoint: 'cat.recovery', params: CatRecoveryParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['recovery']>;
// (undocumented)
(endpoint: 'cat.repositories', params: CatCommonParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['repositories']>;
// (undocumented)
(endpoint: 'cat.segments', params: CatSegmentsParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['segments']>;
// (undocumented)
(endpoint: 'cat.shards', params: CatShardsParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['shards']>;
// (undocumented)
(endpoint: 'cat.snapshots', params: CatSnapshotsParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['snapshots']>;
// (undocumented)
(endpoint: 'cat.tasks', params: CatTasksParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['tasks']>;
// (undocumented)
(endpoint: 'cat.threadPool', params: CatThreadPoolParams, options?: LegacyCallAPIOptions): ReturnType<Client['cat']['threadPool']>;
// (undocumented)
(endpoint: 'cluster.allocationExplain', params: ClusterAllocationExplainParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['allocationExplain']>;
// (undocumented)
(endpoint: 'cluster.getSettings', params: ClusterGetSettingsParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['getSettings']>;
// (undocumented)
(endpoint: 'cluster.health', params: ClusterHealthParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['health']>;
// (undocumented)
(endpoint: 'cluster.pendingTasks', params: ClusterPendingTasksParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['pendingTasks']>;
// (undocumented)
(endpoint: 'cluster.putSettings', params: ClusterPutSettingsParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['putSettings']>;
// (undocumented)
(endpoint: 'cluster.reroute', params: ClusterRerouteParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['reroute']>;
// (undocumented)
(endpoint: 'cluster.state', params: ClusterStateParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['state']>;
// (undocumented)
(endpoint: 'cluster.stats', params: ClusterStatsParams, options?: LegacyCallAPIOptions): ReturnType<Client['cluster']['stats']>;
// (undocumented)
(endpoint: 'indices.analyze', params: IndicesAnalyzeParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['analyze']>;
// (undocumented)
(endpoint: 'indices.clearCache', params: IndicesClearCacheParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['clearCache']>;
// (undocumented)
(endpoint: 'indices.close', params: IndicesCloseParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['close']>;
// (undocumented)
(endpoint: 'indices.create', params: IndicesCreateParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['create']>;
// (undocumented)
(endpoint: 'indices.delete', params: IndicesDeleteParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['delete']>;
// (undocumented)
(endpoint: 'indices.deleteAlias', params: IndicesDeleteAliasParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['deleteAlias']>;
// (undocumented)
(endpoint: 'indices.deleteTemplate', params: IndicesDeleteTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['deleteTemplate']>;
// (undocumented)
(endpoint: 'indices.exists', params: IndicesExistsParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['exists']>;
// (undocumented)
(endpoint: 'indices.existsAlias', params: IndicesExistsAliasParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['existsAlias']>;
// (undocumented)
(endpoint: 'indices.existsTemplate', params: IndicesExistsTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['existsTemplate']>;
// (undocumented)
(endpoint: 'indices.existsType', params: IndicesExistsTypeParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['existsType']>;
// (undocumented)
(endpoint: 'indices.flush', params: IndicesFlushParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['flush']>;
// (undocumented)
(endpoint: 'indices.flushSynced', params: IndicesFlushSyncedParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['flushSynced']>;
// (undocumented)
(endpoint: 'indices.forcemerge', params: IndicesForcemergeParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['forcemerge']>;
// (undocumented)
(endpoint: 'indices.get', params: IndicesGetParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['get']>;
// (undocumented)
(endpoint: 'indices.getAlias', params: IndicesGetAliasParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['getAlias']>;
// (undocumented)
(endpoint: 'indices.getFieldMapping', params: IndicesGetFieldMappingParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['getFieldMapping']>;
// (undocumented)
(endpoint: 'indices.getMapping', params: IndicesGetMappingParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['getMapping']>;
// (undocumented)
(endpoint: 'indices.getSettings', params: IndicesGetSettingsParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['getSettings']>;
// (undocumented)
(endpoint: 'indices.getTemplate', params: IndicesGetTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['getTemplate']>;
// (undocumented)
(endpoint: 'indices.getUpgrade', params: IndicesGetUpgradeParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['getUpgrade']>;
// (undocumented)
(endpoint: 'indices.open', params: IndicesOpenParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['open']>;
// (undocumented)
(endpoint: 'indices.putAlias', params: IndicesPutAliasParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['putAlias']>;
// (undocumented)
(endpoint: 'indices.putMapping', params: IndicesPutMappingParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['putMapping']>;
// (undocumented)
(endpoint: 'indices.putSettings', params: IndicesPutSettingsParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['putSettings']>;
// (undocumented)
(endpoint: 'indices.putTemplate', params: IndicesPutTemplateParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['putTemplate']>;
// (undocumented)
(endpoint: 'indices.recovery', params: IndicesRecoveryParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['recovery']>;
// (undocumented)
(endpoint: 'indices.refresh', params: IndicesRefreshParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['refresh']>;
// (undocumented)
(endpoint: 'indices.rollover', params: IndicesRolloverParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['rollover']>;
// (undocumented)
(endpoint: 'indices.segments', params: IndicesSegmentsParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['segments']>;
// (undocumented)
(endpoint: 'indices.shardStores', params: IndicesShardStoresParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['shardStores']>;
// (undocumented)
(endpoint: 'indices.shrink', params: IndicesShrinkParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['shrink']>;
// (undocumented)
(endpoint: 'indices.stats', params: IndicesStatsParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['stats']>;
// (undocumented)
(endpoint: 'indices.updateAliases', params: IndicesUpdateAliasesParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['updateAliases']>;
// (undocumented)
(endpoint: 'indices.upgrade', params: IndicesUpgradeParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['upgrade']>;
// (undocumented)
(endpoint: 'indices.validateQuery', params: IndicesValidateQueryParams, options?: LegacyCallAPIOptions): ReturnType<Client['indices']['validateQuery']>;
// (undocumented)
(endpoint: 'ingest.deletePipeline', params: IngestDeletePipelineParams, options?: LegacyCallAPIOptions): ReturnType<Client['ingest']['deletePipeline']>;
// (undocumented)
(endpoint: 'ingest.getPipeline', params: IngestGetPipelineParams, options?: LegacyCallAPIOptions): ReturnType<Client['ingest']['getPipeline']>;
// (undocumented)
(endpoint: 'ingest.putPipeline', params: IngestPutPipelineParams, options?: LegacyCallAPIOptions): ReturnType<Client['ingest']['putPipeline']>;
// (undocumented)
(endpoint: 'ingest.simulate', params: IngestSimulateParams, options?: LegacyCallAPIOptions): ReturnType<Client['ingest']['simulate']>;
// (undocumented)
(endpoint: 'nodes.hotThreads', params: NodesHotThreadsParams, options?: LegacyCallAPIOptions): ReturnType<Client['nodes']['hotThreads']>;
// (undocumented)
(endpoint: 'nodes.info', params: NodesInfoParams, options?: LegacyCallAPIOptions): ReturnType<Client['nodes']['info']>;
// (undocumented)
(endpoint: 'nodes.stats', params: NodesStatsParams, options?: LegacyCallAPIOptions): ReturnType<Client['nodes']['stats']>;
// (undocumented)
(endpoint: 'snapshot.create', params: SnapshotCreateParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['create']>;
// (undocumented)
(endpoint: 'snapshot.createRepository', params: SnapshotCreateRepositoryParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['createRepository']>;
// (undocumented)
(endpoint: 'snapshot.delete', params: SnapshotDeleteParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['delete']>;
// (undocumented)
(endpoint: 'snapshot.deleteRepository', params: SnapshotDeleteRepositoryParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['deleteRepository']>;
// (undocumented)
(endpoint: 'snapshot.get', params: SnapshotGetParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['get']>;
// (undocumented)
(endpoint: 'snapshot.getRepository', params: SnapshotGetRepositoryParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['getRepository']>;
// (undocumented)
(endpoint: 'snapshot.restore', params: SnapshotRestoreParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['restore']>;
// (undocumented)
(endpoint: 'snapshot.status', params: SnapshotStatusParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['status']>;
// (undocumented)
(endpoint: 'snapshot.verifyRepository', params: SnapshotVerifyRepositoryParams, options?: LegacyCallAPIOptions): ReturnType<Client['snapshot']['verifyRepository']>;
// (undocumented)
(endpoint: 'tasks.cancel', params: TasksCancelParams, options?: LegacyCallAPIOptions): ReturnType<Client['tasks']['cancel']>;
// (undocumented)
(endpoint: 'tasks.get', params: TasksGetParams, options?: LegacyCallAPIOptions): ReturnType<Client['tasks']['get']>;
// (undocumented)
(endpoint: 'tasks.list', params: TasksListParams, options?: LegacyCallAPIOptions): ReturnType<Client['tasks']['list']>;
// (undocumented)
(endpoint: 'transport.request', clientParams: AssistantAPIClientParams, options?: LegacyCallAPIOptions): Promise<AssistanceAPIResponse>;
// (undocumented)
(endpoint: 'transport.request', clientParams: DeprecationAPIClientParams, options?: LegacyCallAPIOptions): Promise<DeprecationAPIResponse>;
// (undocumented)
<T = any>(endpoint: string, clientParams?: Record<string, any>, options?: LegacyCallAPIOptions): Promise<T>;
}
// @public @deprecated
export interface LegacyCallAPIOptions {
signal?: AbortSignal;
wrap401Errors?: boolean;
}
// @public @deprecated
export class LegacyClusterClient implements ILegacyClusterClient {
constructor(config: LegacyElasticsearchClientConfig, log: Logger, type: string, getAuthHeaders?: GetAuthHeaders);
asScoped(request?: ScopeableRequest): ILegacyScopedClusterClient;
// @deprecated
callAsInternalUser: LegacyAPICaller;
close(): void;
}
// @public @deprecated (undocumented)
export type LegacyElasticsearchClientConfig = Pick<ConfigOptions, 'keepAlive' | 'log' | 'plugins'> & Pick<ElasticsearchConfig, 'apiVersion' | 'customHeaders' | 'requestHeadersWhitelist' | 'sniffOnStart' | 'sniffOnConnectionFault' | 'hosts' | 'username' | 'password' | 'serviceAccountToken'> & {
pingTimeout?: ElasticsearchConfig['pingTimeout'] | ConfigOptions['pingTimeout'];
requestTimeout?: ElasticsearchConfig['requestTimeout'] | ConfigOptions['requestTimeout'];
sniffInterval?: ElasticsearchConfig['sniffInterval'] | ConfigOptions['sniffInterval'];
ssl?: Partial<ElasticsearchConfig['ssl']>;
};
// @public
export interface LegacyElasticsearchError extends Boom.Boom {
// (undocumented)
[code_2]?: string;
}
// @public
export class LegacyElasticsearchErrorHelpers {
// (undocumented)
static decorateNotAuthorizedError(error: Error, reason?: string): LegacyElasticsearchError;
// (undocumented)
static isNotAuthorizedError(error: any): error is LegacyElasticsearchError;
}
// @public @deprecated (undocumented)
export interface LegacyRequest extends Request {
}
// @public @deprecated
export class LegacyScopedClusterClient implements ILegacyScopedClusterClient {
constructor(internalAPICaller: LegacyAPICaller, scopedAPICaller: LegacyAPICaller, headers?: Headers | undefined);
// @deprecated
callAsCurrentUser(endpoint: string, clientParams?: Record<string, any>, options?: LegacyCallAPIOptions): Promise<any>;
// @deprecated
callAsInternalUser(endpoint: string, clientParams?: Record<string, any>, options?: LegacyCallAPIOptions): Promise<any>;
}
// Warning: (ae-forgotten-export) The symbol "lifecycleResponseFactory" needs to be exported by the entry point index.d.ts
//
// @public
@ -1793,12 +1316,6 @@ export interface MetricsServiceSetup {
// @public
export type MetricsServiceStart = MetricsServiceSetup;
// @public @deprecated (undocumented)
export type MIGRATION_ASSISTANCE_INDEX_ACTION = 'upgrade' | 'reindex';
// @public @deprecated (undocumented)
export type MIGRATION_DEPRECATION_LEVEL = 'none' | 'info' | 'warning' | 'critical';
// @public
export type MutatingOperationRefreshSetting = boolean | 'wait_for';
@ -2090,6 +1607,8 @@ export interface RegisterDeprecationsConfig {
// @public
export type RequestHandler<P = unknown, Q = unknown, B = unknown, Context extends RequestHandlerContext = RequestHandlerContext, Method extends RouteMethod = any, ResponseFactory extends KibanaResponseFactory = KibanaResponseFactory> = (context: Context, request: KibanaRequest<P, Q, B, Method>, response: ResponseFactory) => IKibanaResponse<any> | Promise<IKibanaResponse<any>>;
// Warning: (ae-unresolved-link) The @link reference could not be resolved: The package "kibana" does not have an export "LegacyScopedClusterClient"
//
// @public
export interface RequestHandlerContext {
// (undocumented)
@ -2103,9 +1622,6 @@ export interface RequestHandlerContext {
};
elasticsearch: {
client: IScopedClusterClient;
legacy: {
client: ILegacyScopedClusterClient;
};
};
uiSettings: {
client: IUiSettingsClient;

View file

@ -699,7 +699,7 @@ export class Plugin implements Plugin_2<PluginSetup, PluginStart, DataPluginSetu
start(core: CoreStart_2, { fieldFormats }: DataPluginStartDependencies): {
fieldFormats: FieldFormatsStart;
indexPatterns: {
indexPatternsServiceFactory: (savedObjectsClient: Pick<import("../../../core/server").SavedObjectsClient, "update" | "get" | "delete" | "create" | "bulkCreate" | "checkConflicts" | "find" | "bulkGet" | "resolve" | "collectMultiNamespaceReferences" | "updateObjectsSpaces" | "bulkUpdate" | "removeReferencesTo" | "openPointInTimeForType" | "closePointInTime" | "createPointInTimeFinder" | "errors">, elasticsearchClient: import("../../../core/server").ElasticsearchClient) => Promise<import(".").IndexPatternsService>;
indexPatternsServiceFactory: (savedObjectsClient: Pick<import("../../../core/server").SavedObjectsClient, "update" | "get" | "closePointInTime" | "create" | "delete" | "bulkCreate" | "checkConflicts" | "find" | "bulkGet" | "resolve" | "collectMultiNamespaceReferences" | "updateObjectsSpaces" | "bulkUpdate" | "removeReferencesTo" | "openPointInTimeForType" | "createPointInTimeFinder" | "errors">, elasticsearchClient: import("../../../core/server").ElasticsearchClient) => Promise<import(".").IndexPatternsService>;
};
search: ISearchStart<import("./search").IEsSearchRequest, import("./search").IEsSearchResponse<any>>;
};

View file

@ -22,8 +22,10 @@ export class CorePluginAPlugin implements Plugin {
'pluginA',
(context) => {
return {
ping: () =>
context.core.elasticsearch.legacy.client.callAsInternalUser('ping') as Promise<string>,
ping: async () => {
const { body } = await context.core.elasticsearch.client.asInternalUser.ping();
return String(body);
},
};
}
);

View file

@ -10,7 +10,6 @@ import { Capabilities } from 'src/core/server';
import {
savedObjectsTypeRegistryMock,
savedObjectsClientMock,
elasticsearchServiceMock,
uiSettingsServiceMock,
capabilitiesServiceMock,
} from '../../../../../src/core/server/mocks';
@ -22,11 +21,6 @@ const createContextMock = (capabilities: Partial<Capabilities> = {}) => {
client: savedObjectsClientMock.create(),
typeRegistry: savedObjectsTypeRegistryMock.create(),
},
elasticsearch: {
legacy: {
client: elasticsearchServiceMock.createLegacyScopedClusterClient(),
},
},
uiSettings: {
client: uiSettingsServiceMock.createClient(),
},

View file

@ -21,9 +21,6 @@ describe('getContextFactory', () => {
expect(coreStart.savedObjects.getTypeRegistry).toHaveBeenCalledTimes(1);
expect(coreStart.elasticsearch.legacy.client.asScoped).toHaveBeenCalledTimes(1);
expect(coreStart.elasticsearch.legacy.client.asScoped).toHaveBeenCalledWith(request);
const soClient = coreStart.savedObjects.getScopedClient.mock.results[0].value;
expect(coreStart.uiSettings.asScopedToClient).toHaveBeenCalledTimes(1);
expect(coreStart.uiSettings.asScopedToClient).toHaveBeenCalledWith(soClient);
@ -34,7 +31,6 @@ describe('getContextFactory', () => {
expect(context).toEqual({
core: {
savedObjects: expect.any(Object),
elasticsearch: expect.any(Object),
uiSettings: expect.any(Object),
capabilities: expect.any(Object),
},

View file

@ -24,11 +24,6 @@ export const getContextFactory = (coreStart: CoreStart) => (
client: soClient,
typeRegistry: coreStart.savedObjects.getTypeRegistry(),
},
elasticsearch: {
legacy: {
client: coreStart.elasticsearch.legacy.client.asScoped(request),
},
},
uiSettings: {
client: coreStart.uiSettings.asScopedToClient(soClient),
},

View file

@ -8,7 +8,6 @@
import { Observable } from 'rxjs';
import type {
ISavedObjectTypeRegistry,
ILegacyScopedClusterClient,
IUiSettingsClient,
SavedObjectsClientContract,
Capabilities,
@ -68,11 +67,6 @@ export interface GlobalSearchProviderContext {
client: SavedObjectsClientContract;
typeRegistry: ISavedObjectTypeRegistry;
};
elasticsearch: {
legacy: {
client: ILegacyScopedClusterClient;
};
};
uiSettings: {
client: IUiSettingsClient;
};

View file

@ -11,7 +11,6 @@ import { RacRequestHandlerContext } from '../../types';
const createMockClients = () => ({
rac: alertsClientMock.create(),
clusterClient: elasticsearchServiceMock.createLegacyScopedClusterClient(),
newClusterClient: elasticsearchServiceMock.createScopedClusterClient(),
savedObjectsClient: savedObjectsClientMock.create(),
});
@ -27,7 +26,6 @@ const createRequestContextMock = (
elasticsearch: {
...coreContext.elasticsearch,
client: clients.newClusterClient,
legacy: { ...coreContext.elasticsearch.legacy, client: clients.clusterClient },
},
savedObjects: { client: clients.savedObjectsClient },
},

View file

@ -22,7 +22,6 @@ import {
GeoContainmentInstanceState,
GeoContainmentParams,
} from '../alert_type';
import { SearchResponse } from 'elasticsearch';
const alertInstanceFactory = (contextKeys: unknown[], testAlertActionArr: unknown[]) => (
instanceId: string
@ -53,7 +52,7 @@ describe('geo_containment', () => {
it('should correctly transform expected results', async () => {
const transformedResults = transformResults(
// @ts-ignore
(sampleAggsJsonResponse.body as unknown) as SearchResponse<unknown>,
sampleAggsJsonResponse.body,
dateField,
geoField
);
@ -113,7 +112,7 @@ describe('geo_containment', () => {
it('should correctly transform expected results if fields are nested', async () => {
const transformedResults = transformResults(
// @ts-ignore
(sampleAggsJsonResponseWithNesting.body as unknown) as SearchResponse<unknown>,
sampleAggsJsonResponseWithNesting.body,
nestedDateField,
nestedGeoField
);

View file

@ -90,7 +90,7 @@ export class SampleTaskManagerFixturePlugin
req: KibanaRequest<any, any, any, any>,
res: KibanaResponseFactory
): Promise<IKibanaResponse<any>> {
await core.elasticsearch.legacy.client.callAsInternalUser('indices.refresh', {
await context.core.elasticsearch.client.asInternalUser.indices.refresh({
index: '.kibana_task_manager',
});
return res.ok({ body: {} });

View file

@ -12,7 +12,7 @@ import {
KibanaResponseFactory,
IKibanaResponse,
IRouter,
CoreSetup,
IScopedClusterClient,
} from 'src/core/server';
import { EventEmitter } from 'events';
import { TaskManagerStartContract } from '../../../../../plugins/task_manager/server';
@ -36,12 +36,11 @@ const taskManagerQuery = {
export function initRoutes(
router: IRouter,
core: CoreSetup,
taskManagerStart: Promise<TaskManagerStartContract>,
taskTestingEvents: EventEmitter
) {
async function ensureIndexIsRefreshed() {
return await core.elasticsearch.legacy.client.callAsInternalUser('indices.refresh', {
async function ensureIndexIsRefreshed(client: IScopedClusterClient) {
return await client.asInternalUser.indices.refresh({
index: '.kibana_task_manager',
});
}
@ -250,7 +249,7 @@ export function initRoutes(
res: KibanaResponseFactory
): Promise<IKibanaResponse<any>> {
try {
await ensureIndexIsRefreshed();
await ensureIndexIsRefreshed(context.core.elasticsearch.client);
const taskManager = await taskManagerStart;
return res.ok({ body: await taskManager.get(req.params.taskId) });
} catch ({ isBoom, output, message }) {
@ -269,7 +268,7 @@ export function initRoutes(
req: KibanaRequest<any, any, any, any>,
res: KibanaResponseFactory
): Promise<IKibanaResponse<any>> {
await ensureIndexIsRefreshed();
await ensureIndexIsRefreshed(context.core.elasticsearch.client);
return res.ok({ body: {} });
}
);
@ -285,7 +284,7 @@ export function initRoutes(
res: KibanaResponseFactory
): Promise<IKibanaResponse<any>> {
try {
await ensureIndexIsRefreshed();
await ensureIndexIsRefreshed(context.core.elasticsearch.client);
let tasksFound = 0;
const taskManager = await taskManagerStart;
do {

View file

@ -69,7 +69,8 @@ export class SampleTaskManagerFixturePlugin
}
}
await core.elasticsearch.legacy.client.callAsInternalUser('index', {
const [{ elasticsearch }] = await core.getStartServices();
await elasticsearch.client.asInternalUser.index({
index: '.kibana_task_manager_test_result',
body: {
type: 'task',
@ -270,7 +271,7 @@ export class SampleTaskManagerFixturePlugin
return context;
},
});
initRoutes(core.http.createRouter(), core, this.taskManagerStart, taskTestingEvents);
initRoutes(core.http.createRouter(), this.taskManagerStart, taskTestingEvents);
}
public start(core: CoreStart, { taskManager }: SampleTaskManagerFixtureStartDeps) {

View file

@ -12363,7 +12363,7 @@ elastic-apm-node@^3.16.0:
traverse "^0.6.6"
unicode-byte-truncate "^1.0.0"
elasticsearch@^16.4.0, elasticsearch@^16.7.0:
elasticsearch@^16.4.0:
version "16.7.0"
resolved "https://registry.yarnpkg.com/elasticsearch/-/elasticsearch-16.7.0.tgz#9055e3f586934d8de5fd407b04050e9d54173333"
integrity sha512-du+//TbjCFEkaG0jNcAC95Fp4B6/X5shnCRIXALFL+M4U5iT3YL5ZVUPNf1NgR7dy/sc8Dvw2Ob6IUJKB7FrCw==