forked from kelseyhightower/confd
/
client.go
209 lines (183 loc) · 5.37 KB
/
client.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
package vault
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"path"
vaultapi "github.com/hashicorp/vault/api"
"github.com/kelseyhightower/confd/log"
)
// Client is a wrapper around the vault client
type Client struct {
client *vaultapi.Client
}
// get a
func getParameter(key string, parameters map[string]string) string {
value := parameters[key]
if value == "" {
// panic if a configuration is missing
panic(fmt.Sprintf("%s is missing from configuration", key))
}
return value
}
// panicToError converts a panic to an error
func panicToError(err *error) {
if r := recover(); r != nil {
switch t := r.(type) {
case string:
*err = errors.New(t)
case error:
*err = t
default: // panic again if we don't know how to handle
panic(r)
}
}
}
// authenticate with the remote client
func authenticate(c *vaultapi.Client, authType string, params map[string]string) (err error) {
var secret *vaultapi.Secret
// handle panics gracefully by creating an error
// this would happen when we get a parameter that is missing
defer panicToError(&err)
switch authType {
case "app-id":
secret, err = c.Logical().Write("/auth/app-id/login", map[string]interface{}{
"app_id": getParameter("app-id", params),
"user_id": getParameter("user-id", params),
})
case "github":
secret, err = c.Logical().Write("/auth/github/login", map[string]interface{}{
"token": getParameter("token", params),
})
case "token":
c.SetToken(getParameter("token", params))
secret, err = c.Logical().Read("/auth/token/lookup-self")
case "userpass":
username, password := getParameter("username", params), getParameter("password", params)
secret, err = c.Logical().Write(fmt.Sprintf("/auth/userpass/login/%s", username), map[string]interface{}{
"password": password,
})
}
if err != nil {
return err
}
// if the token has already been set
if c.Token() != "" {
return nil
}
log.Debug("client authenticated with auth backend: %s", authType)
// the default place for a token is in the auth section
// otherwise, the backend will set the token itself
c.SetToken(secret.Auth.ClientToken)
return nil
}
func getConfig(address, cert, key, caCert string) (*vaultapi.Config, error) {
conf := vaultapi.DefaultConfig()
conf.Address = address
tlsConfig := &tls.Config{}
if cert != "" && key != "" {
clientCert, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
return nil, err
}
tlsConfig.Certificates = []tls.Certificate{clientCert}
tlsConfig.BuildNameToCertificate()
}
if caCert != "" {
ca, err := ioutil.ReadFile(caCert)
if err != nil {
return nil, err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(ca)
tlsConfig.RootCAs = caCertPool
}
conf.HttpClient.Transport = &http.Transport{
TLSClientConfig: tlsConfig,
}
return conf, nil
}
// New returns an *vault.Client with a connection to named machines.
// It returns an error if a connection to the cluster cannot be made.
func New(address, authType string, params map[string]string) (*Client, error) {
if authType == "" {
return nil, errors.New("you have to set the auth type when using the vault backend")
}
log.Info("Vault authentication backend set to %s", authType)
conf, err := getConfig(address, params["cert"], params["key"], params["caCert"])
if err != nil {
return nil, err
}
c, err := vaultapi.NewClient(conf)
if err != nil {
return nil, err
}
if err := authenticate(c, authType, params); err != nil {
return nil, err
}
return &Client{c}, nil
}
// GetValues queries etcd for keys prefixed by prefix.
func (c *Client) GetValues(keys []string) (map[string]string, error) {
vars := make(map[string]string)
for _, key := range keys {
log.Debug("getting %s from vault", key)
resp, err := c.client.Logical().Read(key)
if err != nil {
log.Debug("there was an error extracting %s", key)
return nil, err
}
if resp == nil || resp.Data == nil {
continue
}
// if the key has only one string value
// treat it as a string and not a map of values
if val, ok := isKV(resp.Data); ok {
vars[key] = val
} else {
// save the json encoded response
// and flatten it to allow usage of gets & getvs
js, _ := json.Marshal(resp.Data)
vars[key] = string(js)
flatten(key, resp.Data, vars)
}
}
return vars, nil
}
// isKV checks if a given map has only one key of type string
// if so, returns the value of that key
func isKV(data map[string]interface{}) (string, bool) {
if len(data) == 1 {
if value, ok := data["value"]; ok {
if text, ok := value.(string); ok {
return text, true
}
}
}
return "", false
}
// recursively walks on all the values of a specific key and set them in the variables map
func flatten(key string, value interface{}, vars map[string]string) {
switch value.(type) {
case string:
log.Debug("setting key %s to: %s", key, value)
vars[key] = value.(string)
case map[string]interface{}:
inner := value.(map[string]interface{})
for innerKey, innerValue := range inner {
innerKey = path.Join(key, "/", innerKey)
flatten(innerKey, innerValue, vars)
}
default: // we don't know how to handle non string or maps of strings
log.Warning("type of '%s' is not supported (%T)", key, value)
}
}
// WatchPrefix - not implemented at the moment
func (c *Client) WatchPrefix(prefix string, keys []string, waitIndex uint64, stopChan chan bool) (uint64, error) {
<-stopChan
return 0, nil
}