/
kubeconfig.go
556 lines (469 loc) · 14.8 KB
/
kubeconfig.go
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
package auth
import (
"bytes"
"errors"
"fmt"
"os"
"path"
"github.com/icza/dyno"
"gopkg.in/yaml.v3"
)
//
// kubeconfig provides methods to read and write kuberentes kubectl-config-files.
// It must not depend on the k8s.io-client due to the dependency-hell surrounding it.
// So we tried to be generic and structure agnostic, so that we can read a config,
// modify just the parts we need and write it back and do not loose anything,
// we don't want to know and care about.
// It would be much easier to un/marshall structs, but then we would be in danger
// of loosing fields that we don't have in our version.
//
const (
oidcAuthProvider = "oidc"
)
// UserIDExtractor extractor to make the source of the "userid" customizable
type UserIDExtractor func(tokenInfo TokenInfo) string
func ExtractName(tokenInfo TokenInfo) string {
return tokenInfo.TokenClaims.Username()
}
func ExtractEMail(tokenInfo TokenInfo) string {
return tokenInfo.TokenClaims.EMail
}
// UpdateKubeConfig saves the given tokenInfo in the given kubeConfig. The given path to kubeconfig is preferred,
// otherwise the location of the kubeconfig is determined from env KUBECONFIG or default location.
//
// we modify/append a user with auth-provider from given tokenInfo.
// we modify/append a context with name cloudctl that references the user.
//
// returns filename the config got written to or error if any
//
// Deprecated: use UpdateKubeConfigContext instead
func UpdateKubeConfig(kubeConfig string, tokenInfo TokenInfo, userIDExtractor UserIDExtractor) (string, error) {
return UpdateKubeConfigContext(kubeConfig, tokenInfo, userIDExtractor, cloudContext)
}
// UpdateKubeConfig saves the given tokenInfo in the given kubeConfig. The given path to kubeconfig is preferred,
// otherwise the location of the kubeconfig is determined from env KUBECONFIG or default location.
//
// we modify/append a user with auth-provider from given tokenInfo.
// we modify/append the given context that references the user.
//
// returns filename the config got written to or error if any
func UpdateKubeConfigContext(kubeConfig string, tokenInfo TokenInfo, userIDExtractor UserIDExtractor, contextName string) (string, error) {
if userIDExtractor == nil {
return "", errors.New("userIdExtractor must not be nil")
}
cfg, outputFilename, isDefault, err := LoadKubeConfig(kubeConfig)
if err != nil {
// file does not exist, we create it from scratch
outputFilename = kubeConfig
err = CreateFromTemplate(&cfg)
if err != nil {
return "", err
}
}
usersSlice, err := dyno.GetSlice(cfg, "users")
if err != nil {
usersSlice = make([]interface{}, 0)
}
cfg["users"] = usersSlice
userName := userIDExtractor(tokenInfo)
config := map[string]string{
"client-id": tokenInfo.ClientID,
"client-secret": tokenInfo.ClientSecret,
"id-token": tokenInfo.IDToken,
"refresh-token": tokenInfo.RefreshToken,
"idp-issuer-url": tokenInfo.TokenClaims.Issuer,
"idp-certificate-authority": tokenInfo.IssuerCA,
}
err = AddUserConfigMap(cfg, userName, config)
if err != nil {
return "", err
}
err = AddContext(cfg, contextName, "", userName)
if err != nil {
return "", err
}
// use configured yaml
yamlBytes, err := EncodeKubeconfig(cfg)
if err != nil {
return "", err
}
// if the location of the kubeconfig is not specified explicitly, we create the default path
if isDefault {
err = ensureDirectory(outputFilename)
if err != nil {
return "", err
}
}
err = os.WriteFile(outputFilename, yamlBytes.Bytes(), 0600)
if err != nil {
return "", err
}
return outputFilename, nil
}
//AddUserConfigMap adds the given user-auth-configMap to the kubecfg or replaces an already existing user
func AddUserConfigMap(kubecfg map[interface{}]interface{}, userName string, configMap map[string]string) error {
authProviderMap := map[string]interface{}{
"config": configMap,
"name": "oidc",
}
userMap := map[string]interface{}{
"auth-provider": authProviderMap,
}
user := map[string]interface{}{
"name": userName,
"user": userMap,
}
usersSlice, err := dyno.GetSlice(kubecfg, "users")
if err != nil {
return err
}
if usersSlice == nil {
return errors.New("users slice not found")
}
// check if user already exists
_, index, err := findMapListMap(kubecfg, "users", "name", userName)
if err != nil {
// not found, append
err = dyno.Append(kubecfg, user, "users")
if err != nil {
return err
}
} else {
// replace user
usersSlice[index] = user
}
return nil
}
//AddUser adds the given user-authconfig to the kubecfg or replaces an already existing user
func AddUser(kubecfg map[interface{}]interface{}, authCtx AuthContext) error {
userName := authCtx.User
configMap := map[string]string{
"client-id": authCtx.ClientID,
"client-secret": authCtx.ClientSecret,
"id-token": authCtx.IDToken,
// "refresh-token": authCtx.RefreshToken,
"idp-issuer-url": authCtx.IssuerURL,
"idp-certificate-authority": authCtx.IssuerCA,
}
return AddUserConfigMap(kubecfg, userName, configMap)
}
//AddContext adds or replaces the given context with given clusterName and userName.
func AddContext(cfg map[interface{}]interface{}, contextName string, clusterName string, userName string) error {
type Context struct {
Context map[string]interface{}
Name string
}
// check & create context
ctxData := make(map[string]interface{})
ctxData["cluster"] = clusterName
ctxData["user"] = userName
context := Context{
Name: contextName,
Context: ctxData,
}
//check if "contexts" exists
_, err := dyno.Get(cfg, "contexts")
if err != nil {
// not found, create contexts completely
cfg["contexts"] = []Context{
context,
}
} else {
// "contexts" exist, now find named context within "contexts"
_, index, err := findMapListMap(cfg, "contexts", "name", contextName)
if err != nil {
// context "metalctl" not found
err = dyno.Append(cfg, context, "contexts")
if err != nil {
return err
}
} else {
// update context "metalctl"
ctxList, _ := dyno.GetSlice(cfg, "contexts")
ctxList[index] = context
}
}
return nil
}
//SetCurrentContext sets the current context to the given name
func SetCurrentContext(cfg map[interface{}]interface{}, contextName string) {
cfg["current-context"] = contextName
}
//GetClusterNames returns all clusternames
func GetClusterNames(cfg map[interface{}]interface{}) ([]string, error) {
clusterNames := []string{}
clusters, err := dyno.GetSlice(cfg, "clusters")
if err != nil {
return nil, err
}
for i := range clusters {
m, err := dyno.GetMapS(clusters[i])
if err != nil {
return nil, err
}
cn, ok := m["name"].(string)
if ok && cn != "" {
clusterNames = append(clusterNames, cn)
}
}
return clusterNames, nil
}
//AddCluster adds or replaces the given cluster with given clusterName and data.
func AddCluster(cfg map[interface{}]interface{}, clusterName string, clusterData map[string]interface{}) error {
type Cluster struct {
Cluster map[string]interface{}
Name string
}
cluster := Cluster{
Name: clusterName,
Cluster: clusterData,
}
//check if "clusters" exists
_, err := dyno.Get(cfg, "clusters")
if err != nil {
// not found, create clusters completely
cfg["clusters"] = []Cluster{
cluster,
}
} else {
// "clusters" exist, now find named cluster within "clusters"
_, index, err := findMapListMap(cfg, "clusters", "name", clusterName)
if err != nil {
// cluster name not found
err = dyno.Append(cfg, cluster, "clusters")
if err != nil {
return err
}
} else {
// update cluster
clusterList, _ := dyno.GetSlice(cfg, "clusters")
clusterList[index] = cluster
}
}
return nil
}
//EncodeKubeconfig serializes the given kubeconfig
func EncodeKubeconfig(kubeconfig map[interface{}]interface{}) (bytes.Buffer, error) {
var yamlBytes bytes.Buffer
e := yaml.NewEncoder(&yamlBytes)
e.SetIndent(2)
err := e.Encode(&kubeconfig)
return yamlBytes, err
}
// ensureDirectory checks all directories in fqFile exist and creates if necessary
func ensureDirectory(fqFile string) error {
kcPath := path.Dir(fqFile)
if _, err := os.Stat(kcPath); os.IsNotExist(err) {
return os.MkdirAll(kcPath, 0700)
}
return nil
}
//AuthContext models the data in the kubeconfig user/auth-provider/config/oidc-config-map
type AuthContext struct {
// Name of the context for metalctl auth
Ctx string
// Name of the user in the active context
User string
// Name of the authProvider in the active context
AuthProviderName string
// Flag if the AuthProvider is oidc, i.e. valid for our usecases
AuthProviderOidc bool
// IDToken, only if AuthProviderOidc is true
IDToken string
// RefreshToken
RefreshToken string
IssuerConfig
}
// finds the listKey from the given map, gets the list of maps, finds the map with matchKey == matchValue, returns map, index, error
func findMapListMap(cfg map[interface{}]interface{}, listKey string, matchKey string, matchValue string) (map[string]interface{}, int, error) {
ctxSlice, err := dyno.GetSlice(cfg, listKey)
if err != nil {
return nil, 0, err
}
for i := 0; i < len(ctxSlice); i++ {
currentContextItemMap, err := dyno.GetMapS(ctxSlice[i])
if err != nil {
break
}
if currentContextItemMap[matchKey] == matchValue {
return currentContextItemMap, i, nil
}
}
return nil, 0, fmt.Errorf("no %s, %s=%s found", listKey, matchKey, matchValue)
}
// returns the AuthContext for the default contextName
// Deprecated: use GetAuthContext instead
func CurrentAuthContext(kubeConfig string) (AuthContext, error) {
return GetAuthContext(kubeConfig, cloudContext)
}
// GetAuthContext returns the AuthContext for the given contextName from the given kubeConfig
func GetAuthContext(kubeConfig string, contextName string) (AuthContext, error) {
empty := AuthContext{}
cfg, _, _, err := LoadKubeConfig(kubeConfig)
if err != nil {
return empty, err
}
// get context "metalctl" to determine user
context, _, err := findMapListMap(cfg, "contexts", "name", contextName)
if err != nil {
return empty, err
}
if context == nil {
return empty, fmt.Errorf("cannot determine user from kube-config, context '%s' does not exist", contextName)
}
empty.Ctx = contextName
// determine username from context
contextMap, err := dyno.GetMapS(context, "context")
if err != nil {
return empty, err
}
userName := fmt.Sprintf("%v", contextMap["user"])
empty.User = userName
// get user
userMap, _, err := findMapListMap(cfg, "users", "name", userName)
if err != nil {
return empty, err
}
authProviderMap, err := dyno.GetMapS(userMap, "user", "auth-provider")
if err != nil {
return empty, err
}
// read auth-data
authProviderName, err := dyno.GetString(authProviderMap, "name")
if err != nil {
return empty, err
}
isOidc := authProviderName == oidcAuthProvider
if isOidc {
token, err := dyno.GetString(authProviderMap, "config", "id-token")
if err != nil {
return empty, err
}
issuerURL, err := dyno.GetString(authProviderMap, "config", "idp-issuer-url")
if err != nil {
return empty, err
}
issuerCA, err := dyno.GetString(authProviderMap, "config", "idp-certificate-authority")
if err != nil {
return empty, err
}
clientId, err := dyno.GetString(authProviderMap, "config", "client-id")
if err != nil {
return empty, err
}
clientSecret, err := dyno.GetString(authProviderMap, "config", "client-secret")
if err != nil {
return empty, err
}
return AuthContext{
Ctx: contextName,
User: userName,
AuthProviderName: authProviderName,
AuthProviderOidc: isOidc,
IDToken: token,
IssuerConfig: IssuerConfig{
IssuerURL: issuerURL,
IssuerCA: issuerCA,
ClientID: clientId,
ClientSecret: clientSecret,
},
}, nil
}
return empty, errors.New("cannot determine user from kube-config, no current context set")
}
// LoadKubeConfig loads the kube-config from the given location, if kubeConfig is "" the default location will be used.
// If kubeconfig is explicitly given and no file exists at the location, an error is returned.
// If the default location is used and no file exists, the contents of the kubeconfigTemplate are returned.
// returns map, filename, isDefaultLocation and error
func LoadKubeConfig(kubeConfig string) (content map[interface{}]interface{}, filename string, isDefaultLocation bool, e error) {
var err error
var cfg map[interface{}]interface{}
var outputFilename string
isDefault := false
if kubeConfig != "" {
if _, err = os.Stat(kubeConfig); os.IsNotExist(err) {
// no file, use default
return nil, "", false, fmt.Errorf("error loading kube-config: %w", err)
} else {
// read exactly the specified file
cfg, err = readFile(kubeConfig)
if err != nil {
return nil, "", false, err
}
if len(cfg) == 0 {
return nil, "", false, errors.New("error loading kube-config - config is empty")
}
}
outputFilename = kubeConfig
} else {
// try path from env
envPaths := fromEnv()
if len(envPaths) > 1 {
return nil, "", false, fmt.Errorf("there are multiple files in env %s, don't know which one to update - please use cmdline-option", RecommendedConfigPathEnvVar)
}
if len(envPaths) == 1 {
filename := envPaths[0]
if _, err = os.Stat(filename); os.IsNotExist(err) {
// no file, use default
err = nil
} else {
// read exactly the specified file
cfg, err = readFile(filename)
if err != nil {
return nil, "", false, err
}
}
outputFilename = filename
} else {
// use default location
filename := RecommendedHomeFile
isDefault = true
if _, err = os.Stat(filename); os.IsNotExist(err) {
// no file, use default
err = nil
} else {
// read exactly the specified file
cfg, err = readFile(filename)
if err != nil {
return nil, "", isDefault, err
}
}
outputFilename = filename
}
}
if len(cfg) == 0 {
err = CreateFromTemplate(&cfg)
if err != nil {
return nil, "", isDefault, err
}
}
return cfg, outputFilename, isDefault, err
}
// reads the given yaml-file and unmarshalls the contents (top level map)
// if the file does not exits or if the file is empty, an empty map is returned
func readFile(filename string) (map[interface{}]interface{}, error) {
// we expect a map top level
cfg := make(map[interface{}]interface{})
yamlFile, err := os.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("error reading %s error: %w", filename, err)
}
err = yaml.Unmarshal(yamlFile, cfg)
if err != nil {
return nil, fmt.Errorf("error un-marshalling %s error: %w", filename, err)
}
return cfg, err
}
// minimal kube config
const kubeconfigTemplate = `apiVersion: v1
kind: Config
clusters: []
contexts: []
current-context: ""
preferences: {}
users: []
`
// CreateFromTemplate returns a minimal kubeconfig
func CreateFromTemplate(cfg *map[interface{}]interface{}) error {
return yaml.Unmarshal([]byte(kubeconfigTemplate), cfg)
}