-
Notifications
You must be signed in to change notification settings - Fork 918
/
configure_client.ts
237 lines (213 loc) · 7.39 KB
/
configure_client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
import { Client, ClientOptions } from '@opensearch-project/opensearch';
import { Client as LegacyClient } from 'elasticsearch';
import { AwsSigv4Signer } from '@opensearch-project/opensearch/aws';
import { Logger, OpenSearchDashboardsRequest } from '../../../../../src/core/server';
import {
AuthType,
DataSourceAttributes,
SigV4Content,
SigV4ServiceName,
UsernamePasswordTypedContent,
} from '../../common/data_sources';
import { DataSourcePluginConfigType } from '../../config';
import { CryptographyServiceSetup } from '../cryptography_service';
import { createDataSourceError } from '../lib/error';
import { DataSourceClientParams, ClientParameters } from '../types';
import { parseClientOptions } from './client_config';
import { OpenSearchClientPoolSetup } from './client_pool';
import {
getRootClient,
getAWSCredential,
getCredential,
getDataSource,
getAuthenticationMethod,
generateCacheKey,
} from './configure_client_utils';
import { authRegistryCredentialProvider } from '../util/credential_provider';
export const configureClient = async (
{
dataSourceId,
savedObjects,
cryptography,
testClientDataSourceAttr,
customApiSchemaRegistryPromise,
request,
authRegistry,
}: DataSourceClientParams,
openSearchClientPoolSetup: OpenSearchClientPoolSetup,
config: DataSourcePluginConfigType,
logger: Logger
): Promise<Client> => {
let dataSource;
let requireDecryption = true;
let clientParams;
try {
// configure test client
if (testClientDataSourceAttr) {
const {
auth: { type, credentials },
} = testClientDataSourceAttr;
// handle test connection case when changing non-credential field of existing data source
if (
dataSourceId &&
((type === AuthType.UsernamePasswordType && !credentials?.password) ||
(type === AuthType.SigV4 && !credentials?.accessKey && !credentials?.secretKey))
) {
dataSource = await getDataSource(dataSourceId, savedObjects);
} else {
dataSource = testClientDataSourceAttr;
requireDecryption = false;
}
} else {
dataSource = await getDataSource(dataSourceId!, savedObjects);
}
const authenticationMethod = getAuthenticationMethod(dataSource, authRegistry);
if (authenticationMethod !== undefined) {
clientParams = await authRegistryCredentialProvider(authenticationMethod, {
dataSourceAttr: dataSource,
request,
cryptography,
});
}
const rootClient = getRootClient(
dataSource,
openSearchClientPoolSetup.getClientFromPool,
clientParams
) as Client;
const registeredSchema = (await customApiSchemaRegistryPromise).getAll();
return await getQueryClient(
dataSource,
openSearchClientPoolSetup.addClientToPool,
config,
registeredSchema,
cryptography,
rootClient,
dataSourceId,
request,
clientParams,
requireDecryption
);
} catch (error: any) {
logger.debug(
`Failed to get data source client for dataSourceId: [${dataSourceId}]. ${error}: ${error.stack}`
);
// Re-throw as DataSourceError
throw createDataSourceError(error);
}
};
/**
* Create a child client object with given auth info.
*
* @param rootClient root client for the given data source.
* @param dataSourceAttr data source saved object attributes
* @param registeredSchema registered API schema
* @param cryptography cryptography service for password encryption / decryption
* @param config data source config
* @param addClientToPool function to add client to client pool
* @param dataSourceId id of data source saved Object
* @param request OpenSearch Dashboards incoming request to read client parameters from header.
* @param authRegistry registry to retrieve the credentials provider for the authentication method in order to return the client
* @param requireDecryption false when creating test client before data source exists
* @returns Promise of query client
*/
const getQueryClient = async (
dataSourceAttr: DataSourceAttributes,
addClientToPool: (endpoint: string, authType: AuthType, client: Client | LegacyClient) => void,
config: DataSourcePluginConfigType,
registeredSchema: any[],
cryptography?: CryptographyServiceSetup,
rootClient?: Client,
dataSourceId?: string,
request?: OpenSearchDashboardsRequest,
clientParams?: ClientParameters,
requireDecryption: boolean = true
): Promise<Client> => {
let credential;
let cacheKeySuffix;
let {
auth: { type },
endpoint,
} = dataSourceAttr;
const clientOptions = parseClientOptions(config, endpoint, registeredSchema);
if (clientParams !== undefined) {
credential = clientParams.credentials;
type = clientParams.authType;
cacheKeySuffix = clientParams.cacheKeySuffix;
endpoint = clientParams.endpoint;
if (credential.service === undefined) {
credential = { ...credential, service: dataSourceAttr.auth.credentials?.service };
}
}
const cacheKey = generateCacheKey(endpoint, cacheKeySuffix);
switch (type) {
case AuthType.NoAuth:
if (!rootClient) rootClient = new Client(clientOptions);
addClientToPool(cacheKey, type, rootClient);
return rootClient.child();
case AuthType.UsernamePasswordType:
credential =
(credential as UsernamePasswordTypedContent) ??
(requireDecryption
? await getCredential(dataSourceAttr, cryptography!)
: (dataSourceAttr.auth.credentials as UsernamePasswordTypedContent));
if (!rootClient) rootClient = new Client(clientOptions);
addClientToPool(cacheKey, type, rootClient);
return getBasicAuthClient(rootClient, credential);
case AuthType.SigV4:
credential =
(credential as SigV4Content) ??
(requireDecryption
? await getAWSCredential(dataSourceAttr, cryptography!)
: (dataSourceAttr.auth.credentials as SigV4Content));
if (!rootClient) {
rootClient = getAWSClient(credential, clientOptions);
}
addClientToPool(cacheKey, type, rootClient);
return getAWSChildClient(rootClient, credential);
default:
throw Error(`${type} is not a supported auth type for data source`);
}
};
const getBasicAuthClient = (
rootClient: Client,
credential: UsernamePasswordTypedContent
): Client => {
const { username, password } = credential;
return rootClient.child({
auth: {
username,
password,
},
// Child client doesn't allow auth option, adding null auth header to bypass,
// so logic in child() can rebuild the auth header based on the auth input.
// See https://github.com/opensearch-project/OpenSearch-Dashboards/issues/2182 for details
headers: { authorization: null },
});
};
const getAWSClient = (credential: SigV4Content, clientOptions: ClientOptions): Client => {
const { region } = credential;
return new Client({
...AwsSigv4Signer({
region,
}),
...clientOptions,
});
};
const getAWSChildClient = (rootClient: Client, credential: SigV4Content): Client => {
const { accessKey, secretKey, region, service, sessionToken } = credential;
return rootClient.child({
auth: {
credentials: {
accessKeyId: accessKey,
secretAccessKey: secretKey,
sessionToken: sessionToken ?? '',
},
region,
service: service ?? SigV4ServiceName.OpenSearch,
},
});
};