-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathk8s-client.js
97 lines (81 loc) · 2.18 KB
/
k8s-client.js
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
const k8s = require("@kubernetes/client-node");
const {
newClusters,
newContexts,
newUsers,
} = require("@kubernetes/client-node/dist/config_types");
const { decodeBase64 } = require("./helpers");
function create(api, {
kubeCertificate,
kubeApiServer,
kubeToken,
}) {
const config = getConfig({
kubeCertificate,
kubeApiServer,
kubeToken,
});
const k8sClient = config.makeApiClient(api);
return k8sClient;
}
function getConfig(params) {
const {
kubeCertificate,
kubeApiServer,
kubeToken,
} = params;
const serviceAccountName = extractServiceAccountName(kubeToken);
const cluster = {
cluster: {
"certificate-authority-data": kubeCertificate,
server: kubeApiServer,
},
name: `${serviceAccountName}-cluster`,
};
const context = {
context: {
cluster: `${serviceAccountName}-cluster`,
user: serviceAccountName,
},
name: `${serviceAccountName}-context`,
};
const user = {
name: serviceAccountName,
user: { token: kubeToken },
};
const kubeConfig = new k8s.KubeConfig();
kubeConfig.loadFromOptions({
clusters: newClusters([cluster]),
contexts: newContexts([context]),
users: newUsers([user]),
currentContext: context.name,
});
return kubeConfig;
}
function extractServiceAccountName(kubeToken) {
const possiblePaths = [
["kubernetes.io/serviceaccount/service-account.name"],
["kubernetes.io", "serviceaccount", "name"],
];
try {
const decoded = decodeBase64(kubeToken.split(".")[1]);
const parsed = JSON.parse(decoded);
let serviceAccountName;
const isThereValidPath = possiblePaths.some((path) => typeof (
path.reduce((acc, cur) => {
serviceAccountName = acc[cur] || {};
return serviceAccountName;
}, parsed)
) === "string");
if (!isThereValidPath) {
throw new Error("\"Service Account Name\" was not found in the Access Token.");
}
return serviceAccountName;
} catch (error) {
throw new Error(`Error occured while extracting the Service Account name from the Access Token. Make sure you pass the valid Access Token. ${error}`);
}
}
module.exports = {
create,
extractServiceAccountName,
};