forked from kubernetes-client/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.ts
631 lines (559 loc) · 19.9 KB
/
config.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
import child_process = require('child_process');
import fs = require('fs');
import https = require('https');
import yaml = require('js-yaml');
import net = require('net');
import path = require('path');
import request = require('request');
import WebSocket = require('ws');
import * as api from './api';
import { Authenticator } from './auth';
import { AzureAuth } from './azure_auth';
import {
Cluster,
ConfigOptions,
Context,
exportCluster,
exportContext,
exportUser,
newClusters,
newContexts,
newUsers,
User,
} from './config_types';
import { ExecAuth } from './exec_auth';
import { FileAuth } from './file_auth';
import { GoogleCloudPlatformAuth } from './gcp_auth';
import { DelayedOpenIDConnectAuth } from './oidc_auth_delayed';
// fs.existsSync was removed in node 10
function fileExists(filepath: string): boolean {
try {
fs.accessSync(filepath);
return true;
} catch (ignore) {
return false;
}
}
export class KubeConfig {
private static authenticators: Authenticator[] = [
new AzureAuth(),
new GoogleCloudPlatformAuth(),
new ExecAuth(),
new FileAuth(),
new DelayedOpenIDConnectAuth(),
];
/**
* The list of all known clusters
*/
public 'clusters': Cluster[];
/**
* The list of all known users
*/
public 'users': User[];
/**
* The list of all known contexts
*/
public 'contexts': Context[];
/**
* The name of the current context
*/
public 'currentContext': string;
constructor() {
this.contexts = [];
this.clusters = [];
this.users = [];
}
public getContexts(): Context[] {
return this.contexts;
}
public getClusters(): Cluster[] {
return this.clusters;
}
public getUsers(): User[] {
return this.users;
}
public getCurrentContext(): string {
return this.currentContext;
}
public setCurrentContext(context: string): void {
this.currentContext = context;
}
public getContextObject(name: string): Context | null {
if (!this.contexts) {
return null;
}
return findObject(this.contexts, name, 'context');
}
public getCurrentCluster(): Cluster | null {
const context = this.getCurrentContextObject();
if (!context) {
return null;
}
return this.getCluster(context.cluster);
}
public getCluster(name: string): Cluster | null {
return findObject(this.clusters, name, 'cluster');
}
public getCurrentUser(): User | null {
const ctx = this.getCurrentContextObject();
if (!ctx) {
return null;
}
return this.getUser(ctx.user);
}
public getUser(name: string): User | null {
return findObject(this.users, name, 'user');
}
public loadFromFile(file: string, opts?: Partial<ConfigOptions>): void {
const rootDirectory = path.dirname(file);
this.loadFromString(fs.readFileSync(file, 'utf8'), opts);
this.makePathsAbsolute(rootDirectory);
}
public async applyToHTTPSOptions(opts: https.RequestOptions | WebSocket.ClientOptions): Promise<void> {
await this.applyOptions(opts);
const user = this.getCurrentUser();
if (user && user.username) {
// The ws docs say that it accepts anything that https.RequestOptions accepts,
// but Typescript doesn't understand that idea (yet) probably could be fixed in
// the typings, but for now just cast to any
(opts as any).auth = `${user.username}:${user.password}`;
}
const cluster = this.getCurrentCluster();
if (cluster && cluster.tlsServerName) {
// The ws docs say that it accepts anything that https.RequestOptions accepts,
// but Typescript doesn't understand that idea (yet) probably could be fixed in
// the typings, but for now just cast to any
(opts as any).servername = cluster.tlsServerName;
}
}
public async applyToRequest(opts: request.Options): Promise<void> {
const cluster = this.getCurrentCluster();
const user = this.getCurrentUser();
await this.applyOptions(opts);
if (cluster && cluster.skipTLSVerify) {
opts.strictSSL = false;
}
if (user && user.username) {
opts.auth = {
password: user.password,
username: user.username,
};
}
if (cluster && cluster.tlsServerName) {
opts.agentOptions = { servername: cluster.tlsServerName } as https.AgentOptions;
}
}
public loadFromString(config: string, opts?: Partial<ConfigOptions>): void {
const obj = yaml.load(config) as any;
this.clusters = newClusters(obj.clusters, opts);
this.contexts = newContexts(obj.contexts, opts);
this.users = newUsers(obj.users, opts);
this.currentContext = obj['current-context'];
}
public loadFromOptions(options: {
clusters: Cluster[];
contexts: Context[];
currentContext: Context['name'];
users: User[];
}): void {
this.clusters = options.clusters;
this.contexts = options.contexts;
this.users = options.users;
this.currentContext = options.currentContext;
}
public loadFromClusterAndUser(cluster: Cluster, user: User): void {
this.clusters = [cluster];
this.users = [user];
this.currentContext = 'loaded-context';
this.contexts = [
{
cluster: cluster.name,
user: user.name,
name: this.currentContext,
} as Context,
];
}
public loadFromCluster(pathPrefix: string = ''): void {
const host = process.env.KUBERNETES_SERVICE_HOST;
const port = process.env.KUBERNETES_SERVICE_PORT;
const clusterName = 'inCluster';
const userName = 'inClusterUser';
const contextName = 'inClusterContext';
let scheme = 'https';
if (port === '80' || port === '8080' || port === '8001') {
scheme = 'http';
}
// Wrap raw IPv6 addresses in brackets.
let serverHost = host;
if (host && net.isIPv6(host)) {
serverHost = `[${host}]`;
}
this.clusters = [
{
name: clusterName,
caFile: `${pathPrefix}${Config.SERVICEACCOUNT_CA_PATH}`,
server: `${scheme}://${serverHost}:${port}`,
skipTLSVerify: false,
},
];
this.users = [
{
name: userName,
authProvider: {
name: 'tokenFile',
config: {
tokenFile: `${pathPrefix}${Config.SERVICEACCOUNT_TOKEN_PATH}`,
},
},
},
];
const namespaceFile = `${pathPrefix}${Config.SERVICEACCOUNT_NAMESPACE_PATH}`;
let namespace: string | undefined;
if (fileExists(namespaceFile)) {
namespace = fs.readFileSync(namespaceFile, 'utf8');
}
this.contexts = [
{
cluster: clusterName,
name: contextName,
user: userName,
namespace,
},
];
this.currentContext = contextName;
}
public mergeConfig(config: KubeConfig, preserveContext: boolean = false): void {
if (!preserveContext) {
this.currentContext = config.currentContext;
}
config.clusters.forEach((cluster: Cluster) => {
this.addCluster(cluster);
});
config.users.forEach((user: User) => {
this.addUser(user);
});
config.contexts.forEach((ctx: Context) => {
this.addContext(ctx);
});
}
public addCluster(cluster: Cluster): void {
if (!this.clusters) {
this.clusters = [];
}
this.clusters.forEach((c: Cluster, ix: number) => {
if (c.name === cluster.name) {
throw new Error(`Duplicate cluster: ${c.name}`);
}
});
this.clusters.push(cluster);
}
public addUser(user: User): void {
if (!this.users) {
this.users = [];
}
this.users.forEach((c: User, ix: number) => {
if (c.name === user.name) {
throw new Error(`Duplicate user: ${c.name}`);
}
});
this.users.push(user);
}
public addContext(ctx: Context): void {
if (!this.contexts) {
this.contexts = [];
}
this.contexts.forEach((c: Context, ix: number) => {
if (c.name === ctx.name) {
throw new Error(`Duplicate context: ${c.name}`);
}
});
this.contexts.push(ctx);
}
public loadFromDefault(opts?: Partial<ConfigOptions>, contextFromStartingConfig: boolean = false): void {
if (process.env.KUBECONFIG && process.env.KUBECONFIG.length > 0) {
const files = process.env.KUBECONFIG.split(path.delimiter).filter((filename: string) => filename);
this.loadFromFile(files[0], opts);
for (let i = 1; i < files.length; i++) {
const kc = new KubeConfig();
kc.loadFromFile(files[i], opts);
this.mergeConfig(kc, contextFromStartingConfig);
}
return;
}
const home = findHomeDir();
if (home) {
const config = path.join(home, '.kube', 'config');
if (fileExists(config)) {
this.loadFromFile(config, opts);
return;
}
}
if (process.platform === 'win32') {
try {
const envKubeconfigPathResult = child_process.spawnSync('wsl.exe', [
'bash',
'-c',
'printenv KUBECONFIG',
]);
if (envKubeconfigPathResult.status === 0 && envKubeconfigPathResult.stdout.length > 0) {
const result = child_process.spawnSync('wsl.exe', [
'cat',
envKubeconfigPathResult.stdout.toString('utf8'),
]);
if (result.status === 0) {
this.loadFromString(result.stdout.toString('utf8'), opts);
return;
}
}
} catch (err) {
// Falling back to default kubeconfig
}
try {
const configResult = child_process.spawnSync('wsl.exe', ['cat', '~/.kube/config']);
if (configResult.status === 0) {
this.loadFromString(configResult.stdout.toString('utf8'), opts);
const result = child_process.spawnSync('wsl.exe', ['wslpath', '-w', '~/.kube']);
if (result.status === 0) {
this.makePathsAbsolute(result.stdout.toString('utf8'));
}
return;
}
} catch (err) {
// Falling back to alternative auth
}
}
if (fileExists(Config.SERVICEACCOUNT_TOKEN_PATH)) {
this.loadFromCluster();
return;
}
this.loadFromClusterAndUser(
{ name: 'cluster', server: 'http://localhost:8080' } as Cluster,
{ name: 'user' } as User,
);
}
public makeApiClient<T extends ApiType>(apiClientType: ApiConstructor<T>): T {
const cluster = this.getCurrentCluster();
if (!cluster) {
throw new Error('No active cluster!');
}
const apiClient = new apiClientType(cluster.server);
apiClient.setDefaultAuthentication(this);
return apiClient;
}
public makePathsAbsolute(rootDirectory: string): void {
this.clusters.forEach((cluster: Cluster) => {
if (cluster.caFile) {
cluster.caFile = makeAbsolutePath(rootDirectory, cluster.caFile);
}
});
this.users.forEach((user: User) => {
if (user.certFile) {
user.certFile = makeAbsolutePath(rootDirectory, user.certFile);
}
if (user.keyFile) {
user.keyFile = makeAbsolutePath(rootDirectory, user.keyFile);
}
});
}
public exportConfig(): string {
const configObj = {
apiVersion: 'v1',
kind: 'Config',
clusters: this.clusters.map(exportCluster),
users: this.users.map(exportUser),
contexts: this.contexts.map(exportContext),
preferences: {},
'current-context': this.getCurrentContext(),
};
return JSON.stringify(configObj);
}
private getCurrentContextObject(): Context | null {
return this.getContextObject(this.currentContext);
}
private applyHTTPSOptions(opts: request.Options | https.RequestOptions | WebSocket.ClientOptions): void {
const cluster = this.getCurrentCluster();
const user = this.getCurrentUser();
if (!user) {
return;
}
if (cluster != null && cluster.skipTLSVerify) {
opts.rejectUnauthorized = false;
}
const ca = cluster != null ? bufferFromFileOrString(cluster.caFile, cluster.caData) : null;
if (ca) {
opts.ca = ca;
}
const cert = bufferFromFileOrString(user.certFile, user.certData);
if (cert) {
opts.cert = cert;
}
const key = bufferFromFileOrString(user.keyFile, user.keyData);
if (key) {
opts.key = key;
}
}
private async applyAuthorizationHeader(
opts: request.Options | https.RequestOptions | WebSocket.ClientOptions,
): Promise<void> {
const user = this.getCurrentUser();
if (!user) {
return;
}
const authenticator = KubeConfig.authenticators.find((elt: Authenticator) => {
return elt.isAuthProvider(user);
});
if (!opts.headers) {
opts.headers = {};
}
if (authenticator) {
await authenticator.applyAuthentication(user, opts);
}
if (user.token) {
opts.headers.Authorization = `Bearer ${user.token}`;
}
}
private async applyOptions(
opts: request.Options | https.RequestOptions | WebSocket.ClientOptions,
): Promise<void> {
this.applyHTTPSOptions(opts);
await this.applyAuthorizationHeader(opts);
}
}
export interface ApiType {
defaultHeaders: any;
setDefaultAuthentication(config: api.Authentication): void;
}
type ApiConstructor<T extends ApiType> = new (server: string) => T;
// This class is deprecated and will eventually be removed.
export class Config {
public static SERVICEACCOUNT_ROOT: string = '/var/run/secrets/kubernetes.io/serviceaccount';
public static SERVICEACCOUNT_CA_PATH: string = Config.SERVICEACCOUNT_ROOT + '/ca.crt';
public static SERVICEACCOUNT_TOKEN_PATH: string = Config.SERVICEACCOUNT_ROOT + '/token';
public static SERVICEACCOUNT_NAMESPACE_PATH: string = Config.SERVICEACCOUNT_ROOT + '/namespace';
public static fromFile(filename: string): api.CoreV1Api {
return Config.apiFromFile(filename, api.CoreV1Api);
}
public static fromCluster(): api.CoreV1Api {
return Config.apiFromCluster(api.CoreV1Api);
}
public static defaultClient(): api.CoreV1Api {
return Config.apiFromDefaultClient(api.CoreV1Api);
}
public static apiFromFile<T extends ApiType>(filename: string, apiClientType: ApiConstructor<T>): T {
const kc = new KubeConfig();
kc.loadFromFile(filename);
return kc.makeApiClient(apiClientType);
}
public static apiFromCluster<T extends ApiType>(apiClientType: ApiConstructor<T>): T {
const kc = new KubeConfig();
kc.loadFromCluster();
const cluster = kc.getCurrentCluster();
if (!cluster) {
throw new Error('No active cluster!');
}
const k8sApi = new apiClientType(cluster.server);
k8sApi.setDefaultAuthentication(kc);
return k8sApi;
}
public static apiFromDefaultClient<T extends ApiType>(apiClientType: ApiConstructor<T>): T {
const kc = new KubeConfig();
kc.loadFromDefault();
return kc.makeApiClient(apiClientType);
}
}
export function makeAbsolutePath(root: string, file: string): string {
if (!root || path.isAbsolute(file)) {
return file;
}
return path.join(root, file);
}
// This is public really only for testing.
export function bufferFromFileOrString(file?: string, data?: string): Buffer | null {
if (file) {
return fs.readFileSync(file);
}
if (data) {
return Buffer.from(data, 'base64');
}
return null;
}
function dropDuplicatesAndNils(a: string[]): string[] {
return a.reduce((acceptedValues, currentValue) => {
// Good-enough algorithm for reducing a small (3 items at this point) array into an ordered list
// of unique non-empty strings.
if (currentValue && !acceptedValues.includes(currentValue)) {
return acceptedValues.concat(currentValue);
} else {
return acceptedValues;
}
}, [] as string[]);
}
// Only public for testing.
export function findHomeDir(): string | null {
if (process.platform !== 'win32') {
if (process.env.HOME) {
try {
fs.accessSync(process.env.HOME);
return process.env.HOME;
// tslint:disable-next-line:no-empty
} catch (ignore) {}
}
return null;
}
// $HOME is always favoured, but the k8s go-client prefers the other two env vars
// differently depending on whether .kube/config exists or not.
const homeDrivePath =
process.env.HOMEDRIVE && process.env.HOMEPATH
? path.join(process.env.HOMEDRIVE, process.env.HOMEPATH)
: '';
const homePath = process.env.HOME || '';
const userProfile = process.env.USERPROFILE || '';
const favourHomeDrivePathList: string[] = dropDuplicatesAndNils([homePath, homeDrivePath, userProfile]);
const favourUserProfileList: string[] = dropDuplicatesAndNils([homePath, userProfile, homeDrivePath]);
// 1. the first of %HOME%, %HOMEDRIVE%%HOMEPATH%, %USERPROFILE% containing a `.kube\config` file is returned.
for (const dir of favourHomeDrivePathList) {
try {
fs.accessSync(path.join(dir, '.kube', 'config'));
return dir;
// tslint:disable-next-line:no-empty
} catch (ignore) {}
}
// 2. ...the first of %HOME%, %USERPROFILE%, %HOMEDRIVE%%HOMEPATH% that exists and is writeable is returned
for (const dir of favourUserProfileList) {
try {
fs.accessSync(dir, fs.constants.W_OK);
return dir;
// tslint:disable-next-line:no-empty
} catch (ignore) {}
}
// 3. ...the first of %HOME%, %USERPROFILE%, %HOMEDRIVE%%HOMEPATH% that exists is returned.
for (const dir of favourUserProfileList) {
try {
fs.accessSync(dir);
return dir;
// tslint:disable-next-line:no-empty
} catch (ignore) {}
}
// 4. if none of those locations exists, the first of
// %HOME%, %USERPROFILE%, %HOMEDRIVE%%HOMEPATH% that is set is returned.
return favourUserProfileList[0] || null;
}
export interface Named {
name: string;
}
// Only really public for testing...
export function findObject<T extends Named>(list: T[], name: string, key: string): T | null {
if (!list) {
return null;
}
for (const obj of list) {
if (obj.name === name) {
if (obj[key]) {
obj[key].name = name;
return obj[key];
}
return obj;
}
}
return null;
}