-
Notifications
You must be signed in to change notification settings - Fork 0
/
keychain.go
174 lines (139 loc) · 4.25 KB
/
keychain.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
package main
// Helper methods used to store/fetch keys in MacOS keychain
import (
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"os/exec"
"os/user"
"strings"
"syscall"
"github.com/digitalocean/godo"
"golang.org/x/term"
)
const digitalOceanKeychainKey string = "EWVM: DigitalOcean API token"
const privateSSHKeychainKey string = "EWVM: Private SSH key"
const publicSSHKeychainKey string = "EWVM: Public SSH key"
var validKeyChainServiceKeys = map[string]bool{
digitalOceanKeychainKey: true,
privateSSHKeychainKey: true,
publicSSHKeychainKey: true,
}
func getKeychainKey(key string) (string, error) {
if !validKeyChainServiceKeys[key] {
return "", errors.New("invalid service name when getting keychain key")
}
currentUser, err := user.Current()
if err != nil {
return "", err
}
username := currentUser.Username
out, err := exec.Command("/usr/bin/security", "find-generic-password", "-s", key, "-a", username, "-w").Output()
if err != nil {
return "", err
}
trimmedOutput := strings.TrimSpace(string(out))
outputBytes, err := base64.StdEncoding.DecodeString(trimmedOutput)
if err != nil {
return "", err
}
return string(outputBytes), nil
}
func setKeychainKey(key string, value string) error {
if !validKeyChainServiceKeys[key] {
return errors.New("invalid service name when setting keychain key")
}
currentUser, err := user.Current()
if err != nil {
return err
}
username := currentUser.Username
cmd := exec.Command("/usr/bin/security", "-i")
stdIn, err := cmd.StdinPipe()
if err != nil {
return err
}
if err = cmd.Start(); err != nil {
return err
}
encoded := base64.StdEncoding.EncodeToString([]byte(value))
command := fmt.Sprintf("add-generic-password -U -s '%s' -a %s -w %s\n", key, username, encoded)
if len(command) > 4000 {
return errors.New("input too large for /usr/bin/security to handle interactively via stdin")
}
if _, err := io.WriteString(stdIn, command); err != nil {
return err
}
if err = stdIn.Close(); err != nil {
return err
}
if err = cmd.Wait(); err != nil {
return err
}
return nil
}
func clearKeychainKey(key string) error {
if !validKeyChainServiceKeys[key] {
return errors.New("invalid service name when setting keychain key")
}
currentUser, err := user.Current()
if err != nil {
return err
}
username := currentUser.Username
_, err = exec.Command("/usr/bin/security", "delete-generic-password", "-s", key, "-a", username).Output()
return err
}
func validateOrPromptApiKeySetup() *godo.Client {
apiKey, err := getKeychainKey(digitalOceanKeychainKey)
if err != nil {
// No API key at all, collect from user
apiKey = collectDigitalOceanAPIKey()
}
client := godo.NewFromToken(apiKey)
_, resp, err := client.Account.Get(context.TODO())
if err != nil {
if resp.StatusCode >= 500 && resp.StatusCode < 600 {
Fatalf(fmt.Sprintf("Received %d status code authenticating to DigitalOcean. It may be down: https://status.digitalocean.com/\n\n", resp.StatusCode))
} else {
fmt.Printf("\nAPI token is invalid. Re-enter a valid token.\n\n")
// API key exists but is not valid against the API, collect from user
apiKey = collectDigitalOceanAPIKey()
}
}
client = godo.NewFromToken(apiKey)
_, resp, err = client.Account.Get(context.TODO())
if err != nil {
if resp.StatusCode >= 500 && resp.StatusCode < 600 {
Fatalf(fmt.Sprintf("Received %d status code authenticating to DigitalOcean. It may be down: https://status.digitalocean.com/\n\n", resp.StatusCode))
} else {
// Fresh token collected from the user but is still not valid.
Fatalf("\nCould not collect a valid API token from the user: %s\n", err)
}
}
return client
}
func hasValidApiKeyConfigured() bool {
apiKey, err := getKeychainKey(digitalOceanKeychainKey)
if err != nil {
return false
}
client := godo.NewFromToken(apiKey)
_, _, err = client.Account.Get(context.TODO())
return err == nil
}
func collectDigitalOceanAPIKey() string {
fmt.Print("Enter DigitalOcean API key: ")
keyBytes, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
Fatalf("Unable to collect API key from user: %s\n", err)
}
err = setKeychainKey(digitalOceanKeychainKey, string(keyBytes))
if err != nil {
Fatalf("Unable to set API key in keychain: %s\n", err)
}
fmt.Printf("\n\n")
return string(keyBytes)
}