This repository has been archived by the owner on Sep 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
clean.go
204 lines (177 loc) · 5.99 KB
/
clean.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
// Copyright © 2019 Banzai Cloud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package kubeconfiger
import (
"os"
"path/filepath"
"emperror.dev/errors"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
// cleanConfig collects the minimum needed and supported info from a Kubeconfig structure
func CleanConfig(in *clientcmdapi.Config) (*clientcmdapi.Config, error) {
name := in.CurrentContext
context, ok := in.Contexts[name]
if !ok || context == nil {
return nil, errors.New("can't find referenced current context in Kubeconfig")
}
context, err := cleanContext(context)
if err != nil {
return nil, errors.WrapIf(err, "invalid context block in Kubeconfig")
}
authinfo, ok := in.AuthInfos[context.AuthInfo]
if !ok || authinfo == nil {
return nil, errors.New("can't find referenced user in Kubeconfig")
}
authinfo, err = cleanAuthInfo(authinfo)
if err != nil {
return nil, errors.WrapIf(err, "invalid user block in Kubeconfig")
}
cluster, ok := in.Clusters[context.Cluster]
if !ok || cluster == nil {
return nil, errors.New("can't find referenced cluster in Kubeconfig")
}
cluster, err = cleanCluster(cluster)
if err != nil {
return nil, errors.WrapIf(err, "invalid cluster block in Kubeconfig")
}
out := clientcmdapi.Config{
// Kind -- not needed
// APIVersion -- not needed
// Preferences -- not needed
CurrentContext: name,
Contexts: map[string]*clientcmdapi.Context{name: context},
Clusters: map[string]*clientcmdapi.Cluster{context.Cluster: cluster},
AuthInfos: map[string]*clientcmdapi.AuthInfo{context.AuthInfo: authinfo},
// Extensions -- not needed
}
return &out, nil
}
func cleanContext(in *clientcmdapi.Context) (*clientcmdapi.Context, error) {
out := clientcmdapi.Context{
// LocationOfOrigin -- not needed
Cluster: in.Cluster,
AuthInfo: in.AuthInfo,
Namespace: in.Namespace,
// Extensions -- not needed
}
return &out, nil
}
func cleanAuthInfo(in *clientcmdapi.AuthInfo) (*clientcmdapi.AuthInfo, error) {
execConfig, err := cleanExecConfig(in.Exec)
if err != nil {
return nil, errors.WrapIf(err, "invalid exec field")
}
switch {
case in.ClientCertificate != "":
return nil, errors.New("client certificate files are not supported")
case in.ClientKey != "":
return nil, errors.New("client key files are not supported")
case in.TokenFile != "":
return nil, errors.New("token files are not supported")
case in.AuthProvider != nil && len(in.AuthProvider.Config) > 0:
return nil, errors.New("auth provider configurations are not supported (try exec instead)")
case in.Impersonate != "" || len(in.ImpersonateGroups) > 0:
return nil, errors.New("impoersonation is not supported")
}
out := clientcmdapi.AuthInfo{
// LocationOfOrigin -- not needed
// ClientCertificate -- reads fs
ClientCertificateData: in.ClientCertificateData,
// ClientKey -- reads fs
ClientKeyData: in.ClientKeyData,
Token: in.Token,
// TokenFile -- reads fs
// Impersonate -- not needed
// ImpersonateGroups -- not needed
// ImpersonateUserExtra -- not needed
Username: in.Username,
Password: in.Password,
// AuthProvider -- potentionally insecure, not supported
Exec: execConfig,
// Extensions -- not needed
}
return &out, nil
}
func kubeconfigDir() (string, error) {
configDir := os.Getenv("KUBECONFIGDIR")
if configDir != "" {
return configDir, nil
}
home := os.Getenv("HOME")
if home == "" {
return "", errors.New("no $HOME or $KUBECONFIGDIR environment variable is set")
}
return filepath.Join(home, ".kube"), nil
}
func toKubeBinCommand(command string) (string, error) {
base := filepath.Base(command)
kubeHome, err := kubeconfigDir()
if err != nil {
return "", err
}
command = filepath.Join(kubeHome, "bin", base)
stat, err := os.Stat(command)
if err != nil {
return "", errors.Errorf("can't find %q", command)
}
if stat.IsDir() || stat.Mode()&0100 == 0 { // symlinks and executables are ok
return "", errors.Errorf("%q is not executable (%v)", command, stat.Mode())
}
return command, nil
}
func cleanExecConfig(in *clientcmdapi.ExecConfig) (*clientcmdapi.ExecConfig, error) {
if in == nil {
return nil, nil
}
cmd, err := toKubeBinCommand(in.Command)
if err != nil {
return nil, errors.Errorf("unsupported authenticator command: %v", err)
}
out := clientcmdapi.ExecConfig{
Command: cmd,
Args: in.Args,
Env: in.Env,
APIVersion: in.APIVersion,
}
return &out, nil
}
func cleanCluster(in *clientcmdapi.Cluster) (*clientcmdapi.Cluster, error) {
switch {
case in.CertificateAuthority != "":
return nil, errors.New("CA files are not supported")
}
out := clientcmdapi.Cluster{
// LocationOfOrigin -- not needed
Server: in.Server, // TODO: find out if it's not localhost, cloud api, etc in transport layer (there would be a race condition in dns resolution if checked here)
InsecureSkipTLSVerify: in.InsecureSkipTLSVerify,
// CertificateAuthority -- reads fs
CertificateAuthorityData: in.CertificateAuthorityData,
// Extensions -- not needed
}
return &out, nil
}
// CleanKubeconfig cleans up a serialized kubeconfig and returns it in the same format
func CleanKubeconfig(in []byte) ([]byte, error) {
apiconfig, err := clientcmd.Load(in)
if err != nil {
return nil, errors.WrapIf(err, "failed to load kubernetes API config")
}
apiconfig, err = CleanConfig(apiconfig)
if err != nil {
return nil, err
}
out, err := clientcmd.Write(*apiconfig)
return out, errors.WrapIf(err, "failed to write cleaned kubernetes API config")
}