-
Notifications
You must be signed in to change notification settings - Fork 8.2k
/
api_keys.ts
311 lines (277 loc) · 8.35 KB
/
api_keys.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { ILegacyClusterClient, KibanaRequest, Logger } from '../../../../../src/core/server';
import { SecurityLicense } from '../../common/licensing';
import { HTTPAuthorizationHeader } from './http_authentication';
import { BasicHTTPAuthorizationHeaderCredentials } from './http_authentication';
/**
* Represents the options to create an APIKey class instance that will be
* shared between functions (create, invalidate, etc).
*/
export interface ConstructorOptions {
logger: Logger;
clusterClient: ILegacyClusterClient;
license: SecurityLicense;
}
/**
* Represents the params for creating an API key
*/
export interface CreateAPIKeyParams {
name: string;
role_descriptors: Record<string, any>;
expiration?: string;
}
interface GrantAPIKeyParams {
api_key: CreateAPIKeyParams;
grant_type: 'password' | 'access_token';
username?: string;
password?: string;
access_token?: string;
}
/**
* Represents the params for invalidating an API key
*/
export interface InvalidateAPIKeyParams {
id: string;
}
/**
* The return value when creating an API key in Elasticsearch. The API key returned by this API
* can then be used by sending a request with a Authorization header with a value having the
* prefix ApiKey `{token}` where token is id and api_key joined by a colon `{id}:{api_key}` and
* then encoded to base64.
*/
export interface CreateAPIKeyResult {
/**
* Unique id for this API key
*/
id: string;
/**
* Name for this API key
*/
name: string;
/**
* Optional expiration in milliseconds for this API key
*/
expiration?: number;
/**
* Generated API key
*/
api_key: string;
}
export interface GrantAPIKeyResult {
/**
* Unique id for this API key
*/
id: string;
/**
* Name for this API key
*/
name: string;
/**
* Generated API key
*/
api_key: string;
}
/**
* The return value when invalidating an API key in Elasticsearch.
*/
export interface InvalidateAPIKeyResult {
/**
* The IDs of the API keys that were invalidated as part of the request.
*/
invalidated_api_keys: string[];
/**
* The IDs of the API keys that were already invalidated.
*/
previously_invalidated_api_keys: string[];
/**
* The number of errors that were encountered when invalidating the API keys.
*/
error_count: number;
/**
* Details about these errors. This field is not present in the response when error_count is 0.
*/
error_details?: Array<{
type: string;
reason: string;
caused_by: {
type: string;
reason: string;
};
}>;
}
/**
* Class responsible for managing Elasticsearch API keys.
*/
export class APIKeys {
private readonly logger: Logger;
private readonly clusterClient: ILegacyClusterClient;
private readonly license: SecurityLicense;
constructor({ logger, clusterClient, license }: ConstructorOptions) {
this.logger = logger;
this.clusterClient = clusterClient;
this.license = license;
}
/**
* Determines if API Keys are enabled in Elasticsearch.
*/
async areAPIKeysEnabled(): Promise<boolean> {
if (!this.license.isEnabled()) {
return false;
}
const id = `kibana-api-key-service-test`;
this.logger.debug(
`Testing if API Keys are enabled by attempting to invalidate a non-existant key: ${id}`
);
try {
await this.clusterClient.callAsInternalUser('shield.invalidateAPIKey', {
body: {
id,
},
});
return true;
} catch (e) {
if (this.doesErrorIndicateAPIKeysAreDisabled(e)) {
return false;
}
throw e;
}
}
/**
* Tries to create an API key for the current user.
* @param request Request instance.
* @param params The params to create an API key
*/
async create(
request: KibanaRequest,
params: CreateAPIKeyParams
): Promise<CreateAPIKeyResult | null> {
if (!this.license.isEnabled()) {
return null;
}
this.logger.debug('Trying to create an API key');
// User needs `manage_api_key` privilege to use this API
let result: CreateAPIKeyResult;
try {
result = (await this.clusterClient
.asScoped(request)
.callAsCurrentUser('shield.createAPIKey', { body: params })) as CreateAPIKeyResult;
this.logger.debug('API key was created successfully');
} catch (e) {
this.logger.error(`Failed to create API key: ${e.message}`);
throw e;
}
return result;
}
/**
* Tries to grant an API key for the current user.
* @param request Request instance.
*/
async grantAsInternalUser(request: KibanaRequest, createParams: CreateAPIKeyParams) {
if (!this.license.isEnabled()) {
return null;
}
this.logger.debug('Trying to grant an API key');
const authorizationHeader = HTTPAuthorizationHeader.parseFromRequest(request);
if (authorizationHeader == null) {
throw new Error(
`Unable to grant an API Key, request does not contain an authorization header`
);
}
const params = this.getGrantParams(createParams, authorizationHeader);
// User needs `manage_api_key` or `grant_api_key` privilege to use this API
let result: GrantAPIKeyResult;
try {
result = (await this.clusterClient.callAsInternalUser('shield.grantAPIKey', {
body: params,
})) as GrantAPIKeyResult;
this.logger.debug('API key was granted successfully');
} catch (e) {
this.logger.error(`Failed to grant API key: ${e.message}`);
throw e;
}
return result;
}
/**
* Tries to invalidate an API key.
* @param request Request instance.
* @param params The params to invalidate an API key.
*/
async invalidate(request: KibanaRequest, params: InvalidateAPIKeyParams) {
if (!this.license.isEnabled()) {
return null;
}
this.logger.debug('Trying to invalidate an API key as current user');
let result: InvalidateAPIKeyResult;
try {
// User needs `manage_api_key` privilege to use this API
result = await this.clusterClient
.asScoped(request)
.callAsCurrentUser('shield.invalidateAPIKey', {
body: {
id: params.id,
},
});
this.logger.debug('API key was invalidated successfully as current user');
} catch (e) {
this.logger.error(`Failed to invalidate API key as current user: ${e.message}`);
throw e;
}
return result;
}
/**
* Tries to invalidate an API key by using the internal user.
* @param params The params to invalidate an API key.
*/
async invalidateAsInternalUser(params: InvalidateAPIKeyParams) {
if (!this.license.isEnabled()) {
return null;
}
this.logger.debug('Trying to invalidate an API key');
let result: InvalidateAPIKeyResult;
try {
// Internal user needs `cluster:admin/xpack/security/api_key/invalidate` privilege to use this API
result = await this.clusterClient.callAsInternalUser('shield.invalidateAPIKey', {
body: {
id: params.id,
},
});
this.logger.debug('API key was invalidated successfully');
} catch (e) {
this.logger.error(`Failed to invalidate API key: ${e.message}`);
throw e;
}
return result;
}
private doesErrorIndicateAPIKeysAreDisabled(e: Record<string, any>) {
const disabledFeature = e.body?.error?.['disabled.feature'];
return disabledFeature === 'api_keys';
}
private getGrantParams(
createParams: CreateAPIKeyParams,
authorizationHeader: HTTPAuthorizationHeader
): GrantAPIKeyParams {
if (authorizationHeader.scheme.toLowerCase() === 'bearer') {
return {
api_key: createParams,
grant_type: 'access_token',
access_token: authorizationHeader.credentials,
};
}
if (authorizationHeader.scheme.toLowerCase() === 'basic') {
const basicCredentials = BasicHTTPAuthorizationHeaderCredentials.parseFromCredentials(
authorizationHeader.credentials
);
return {
api_key: createParams,
grant_type: 'password',
username: basicCredentials.username,
password: basicCredentials.password,
};
}
throw new Error(`Unsupported scheme "${authorizationHeader.scheme}" for granting API Key`);
}
}