-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcommon.go
411 lines (331 loc) · 9.33 KB
/
common.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
/*
Copyright © 2021 Christophe Jauffret <[email protected]>
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 cmd
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"path/filepath"
"syscall"
"time"
"github.com/ktr0731/go-fuzzyfinder"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/zalando/go-keyring"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/term"
)
type nutanixCluster struct {
server string
login string
password string
port int
timeout int
insecure bool
}
type karbonCluster struct {
KubeapiServerIpv4Address string `json:"kubeapi_server_ipv4_address"`
Name string `json:"name"`
Status string `json:"status"`
UUID string `json:"uuid"`
Version string `json:"version"`
MasterConfig struct {
DeploymentType string `json:"deployment_type"`
} `json:"master_config"`
}
type kubeConfig struct {
KubeConfig string `json:"kube_config"`
}
type sshConfig struct {
Certificate string `json:"certificate"`
ExpiryTime string `json:"expiry_time"`
PrivateKey string `json:"private_key"`
Username string `json:"username"`
}
func (nutanix *nutanixCluster) selectCluster() (string, error) {
clusters, err := nutanix.listKarbonClusters()
if err != nil {
return "", err
}
idx, err := fuzzyfinder.Find(
clusters,
func(i int) string {
return clusters[i].Name
},
fuzzyfinder.WithPreviewWindow(func(i, w, h int) string {
if i == -1 {
return ""
}
return fmt.Sprintf("%s\n\n status: %s\n version: %s\nAPI endpoint: %s\n type: %s\n uuid: %s",
clusters[i].Name,
clusters[i].Status[1:],
clusters[i].Version,
clusters[i].KubeapiServerIpv4Address,
clusters[i].MasterConfig.DeploymentType,
clusters[i].UUID)
}),
)
if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return "", err
}
return clusters[idx].Name, nil
}
func (nutanix *nutanixCluster) listKarbonClusters() ([]karbonCluster, error) {
karbonListUrl := "/karbon/v1-beta.1/k8s/clusters"
method := "GET"
if verbose {
fmt.Printf("Retrieve cluster list\n")
}
ResponseJSON, err := nutanix.clusterRequest(method, karbonListUrl, nil)
cobra.CheckErr(err)
var clusters []karbonCluster
err = json.Unmarshal([]byte(ResponseJSON), &clusters)
if err != nil {
return nil, err
}
return clusters, nil
}
func saveKeyFile(cluster string, ssh sshConfig, force bool) error {
privateKey := []byte(ssh.PrivateKey)
certificate := []byte(ssh.Certificate)
userHomeDir, err := os.UserHomeDir()
cobra.CheckErr(err)
sshDir := filepath.Join(userHomeDir, ".ssh")
// Create the directory if it does not exist
err = os.MkdirAll(sshDir, 0700)
cobra.CheckErr(err)
// Write the private key
privateKeyFile := filepath.Join(sshDir, cluster)
_, err = os.Stat(privateKeyFile)
if err == nil && !force {
return fmt.Errorf("file %s already exist, use force option to overwrite it", privateKeyFile)
}
err = ioutil.WriteFile(privateKeyFile, privateKey, 0600)
cobra.CheckErr(err)
// Write the certificate
certificateFile := filepath.Join(sshDir, fmt.Sprintf("%s-cert.pub", cluster))
_, err = os.Stat(certificateFile)
if err == nil && !force {
return fmt.Errorf("file %s already exist, use force option to overwrite it", certificateFile)
}
err = ioutil.WriteFile(certificateFile, certificate, 0600)
cobra.CheckErr(err)
if verbose {
fmt.Printf("privateKey file %s successfully written\n", privateKeyFile)
fmt.Printf("certificate file %s successfully written\n", certificateFile)
}
return nil
}
func deleteKeyFile(cluster string) error {
userHomeDir, err := os.UserHomeDir()
if err != nil {
return err
}
sshDir := filepath.Join(userHomeDir, ".ssh")
privateKeyFile := filepath.Join(sshDir, cluster)
err = os.Remove(privateKeyFile)
if err != nil {
return err
}
certificateFile := filepath.Join(sshDir, fmt.Sprintf("%s-cert.pub", cluster))
err = os.Remove(certificateFile)
if err != nil {
return err
}
if verbose {
fmt.Printf("privateKey file %s successfully deleted\n", privateKeyFile)
fmt.Printf("certificate file %s successfully deleted\n", certificateFile)
}
return nil
}
func addKeyAgent(cluster string, ssh sshConfig) error {
expiryTime := ssh.ExpiryTime
privateKey := []byte(ssh.PrivateKey)
certificate := []byte(ssh.Certificate)
// Get the ssh agent
socket := os.Getenv("SSH_AUTH_SOCK")
if socket == "" {
fmt.Println("SSH_AUTH_SOCK environment variable not set")
}
conn, err := net.Dial("unix", socket)
cobra.CheckErr(err)
agentClient := agent.NewClient(conn)
data, _ := pem.Decode(privateKey)
parsedKey, err := x509.ParsePKCS1PrivateKey(data.Bytes)
cobra.CheckErr(err)
sshCert, err := unmarshalCert(certificate)
cobra.CheckErr(err)
now := time.Now()
layout := "2006-01-02T15:04:05.000Z"
futureDate, err := time.Parse(layout, expiryTime)
cobra.CheckErr(err)
diff := futureDate.Sub(now)
err = agentClient.Add(agent.AddedKey{
PrivateKey: parsedKey,
Certificate: sshCert,
Comment: fmt.Sprintf("karbon cluster %s", cluster),
LifetimeSecs: uint32(diff.Seconds()),
})
cobra.CheckErr(err)
if verbose {
fmt.Printf("SSH key for cluster '%s' added to ssh-agent\n", cluster)
}
return nil
}
func deleteKeyAgent(cluster string) error {
// Get the ssh agent
socket := os.Getenv("SSH_AUTH_SOCK")
if socket == "" {
fmt.Println("SSH_AUTH_SOCK environment variable not set")
}
conn, err := net.Dial("unix", socket)
if err != nil {
return err
}
agentClient := agent.NewClient(conn)
keyList, err := agentClient.List()
if err != nil {
return err
}
searchString := fmt.Sprintf("karbon cluster %s", cluster)
for _, key := range keyList {
if key.Comment == searchString {
err = agentClient.Remove(key)
if err != nil {
return err
}
if verbose {
fmt.Printf("SSH key for cluster '%s' deleted from ssh-agent\n", cluster)
}
}
}
return nil
}
func unmarshalCert(bytes []byte) (*ssh.Certificate, error) {
pub, _, _, _, err := ssh.ParseAuthorizedKey(bytes)
if err != nil {
return nil, err
}
cert, ok := pub.(*ssh.Certificate)
if !ok {
return nil, fmt.Errorf("failed to cast to certificate")
}
return cert, nil
}
func getCredentials() (string, string) {
userArg := viper.GetString("user")
keyringFlag := viper.GetBool("keyring")
var password string
var ok bool
var err error
password, ok = os.LookupEnv("KARBON_PASSWORD")
if keyringFlag {
password, err = keyring.Get("kubectl-karbon", userArg)
if err == keyring.ErrNotFound && verbose {
fmt.Printf("No password found in keyring for user %s\n", userArg)
}
if err == nil {
ok = true
}
}
if !ok {
fmt.Printf("Enter %s password:\n", userArg)
bytePassword, err := term.ReadPassword(int(syscall.Stdin))
cobra.CheckErr(err)
password = string(bytePassword)
if keyringFlag {
err = savePasswordKeyring(userArg, password)
cobra.CheckErr(err)
}
}
return userArg, password
}
func savePasswordKeyring(user string, password string) error {
err := keyring.Set("kubectl-karbon", user, password)
if err != nil {
return err
}
if verbose {
fmt.Printf("Password saved in keyring for user %s\n", user)
}
return nil
}
func deletePasswordKeyring(user string) error {
err := keyring.Delete("kubectl-karbon", user)
if err != nil {
return err
}
if verbose {
fmt.Printf("Password deleted from keyring for user %s\n", user)
}
return nil
}
func newNutanixCluster() (*nutanixCluster, error) {
server := viper.GetString("server")
if server == "" {
return nil, fmt.Errorf("error: required flag \"server\" not set")
}
userArg, password := getCredentials()
c := nutanixCluster{
server: server,
login: userArg,
password: password,
port: viper.GetInt("port"),
timeout: viper.GetInt("timeout"),
insecure: viper.GetBool("insecure"),
}
return &c, nil
}
func (c *nutanixCluster) clusterRequest(method string, path string, payload []byte) ([]byte, error) {
customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: c.insecure}
client := &http.Client{Transport: customTransport, Timeout: time.Second * time.Duration(c.timeout)}
requestUrl := fmt.Sprintf("https://%s:%d/%s", c.server, c.port, path)
req, err := http.NewRequest(method, requestUrl, nil)
if err != nil {
return nil, err
}
req.SetBasicAuth(c.login, c.password)
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
switch res.StatusCode {
case 401:
if viper.GetBool("keyring") {
err = deletePasswordKeyring(c.login)
cobra.CheckErr(err)
}
return nil, fmt.Errorf("invalid client credentials")
case 404:
return nil, fmt.Errorf("karbon cluster not found")
case 200:
// OK
default:
return nil, fmt.Errorf("internal Error")
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return body, nil
}