-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.go
More file actions
276 lines (229 loc) · 7.4 KB
/
client.go
File metadata and controls
276 lines (229 loc) · 7.4 KB
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
// Copyright 2020 Ayache Khettar. All rights reserved.
// Use of this source file is governed by MIT license
// license that can be found in LICENSE file.
// Package vault provides a way of loading all the secrets for
// a given Go application or a service into memory. These secrets
// are then available for the application to use at run time.
// Two methods of authentication are supported by this library namely:
// Kubernetes authentication and App role authentication
package vault
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/hashicorp/vault/api"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"net/http"
"os"
)
const (
// AUTH used in the vault REST path for login endpoint
AUTH = "auth"
// ClientToken the json name field of the client token we get in the login response
ClientToken = "client_token"
// JWT vault token header for querying the secrets
JWT = "X-Vault-Token"
// DATA the json field object name representing the secrets
DATA = "data"
// Kubernetes auth
KubernetesAuth = "KUBERNETES"
// App Role
AppRoleAuth = "APP_ROLE"
)
var (
// Info logger
Info *log.Logger
// Error logger
Error *log.Logger
)
func init() {
Info = log.New(os.Stdout,
"INFO: ",
log.Ldate|log.Ltime|log.Llongfile)
Error = log.New(os.Stdout,
"ERROR: ",
log.Ldate|log.Ltime|log.Llongfile)
}
// AuthMethod the authentication method
type AuthMethod string
// Config for vault
type Config struct {
// AuthMethod the authentication method
AuthMethod AuthMethod `yaml:"auth_method"`
// Token the vault kube token path only required fro kube auth method
Token string `yaml:"token"`
// Role The role attached to the JWT vault token
Role string `yaml:"role"`
// SecretPath a string the secret path
SecretPath string `yaml:"secret_path"`
// Address the vault url
Address string `yaml:"address"`
// TLSConfig the tls config
TLSConfig TLSConfig `yaml:"tls_config"`
// RoleId only required for App role auth method
RoleId string `yaml:"role_id"`
//SecretId only required for app role auth method
SecretId string `yaml:"secret_id"`
}
// TLSConfig contains the parameters needed to configure TLS on the HTTP client
// used to communicate with Vault.
type TLSConfig struct {
// CACert is the path to a PEM-encoded CA cert file to use to verify the
// Vault server SSL certificate.
CACert string `yaml:"ca_cert"`
// CAPath is the path to a directory of PEM-encoded CA cert files to verify
// the Vault server SSL certificate.
CAPath string `yaml:"ca_path"`
// ClientCert is the path to the certificate for Vault communication
ClientCert string `yaml:"client_cert"`
// ClientKey is the path to the private key for Vault communication
ClientKey string `yaml:"client_key"`
// TLSServerName, if set, is used to set the SNI host when connecting via
// TLS.
TLSServerName string `yaml:"tls_server_name"`
// Insecure enables or disables SSL verification
Insecure bool `yaml:"insecure"`
}
// SecretLoader used for Vault HTTP client
type SecretLoader struct {
data map[string]interface{}
config Config
}
// KubeAuthBody is the body request for the vault login request
type KubeAuthBody struct {
Role string `json:"role"`
Jwt string `json:"jwt, string"`
}
// AppRoleAuthBody is the body request for the vault login request
type AppRoleAuthBody struct {
RoleID string `json:"role_id"`
SecretID string `json:"secret_id, string"`
}
// LoginRequest
type LoginRequest struct {
Body []byte
Endpoint string
}
// NewClientWithConfig returns an instance of the SecretLoader
func NewClientWithConfig(cf Config) (SecretLoader, error) {
// 1. Login to vault using the provided Token
token, err := Login(cf)
if err != nil {
return SecretLoader{}, err
}
// 2. Load all the secrets
secrets, err := loadAllSecrets(token, cf)
if err != nil {
return SecretLoader{}, err
}
if secrets == nil {
return SecretLoader{}, errors.New("There are no secrets in the given path.")
}
return SecretLoader{data: secrets, config: cf}, nil
}
// NewClient returns an instance of the Secret Loader with the given configuration file
func NewClient(file string) (SecretLoader, error) {
var config Config
cf, err := ioutil.ReadFile(file)
if err != nil {
return SecretLoader{}, err
}
// unmarshall the config
err = yaml.Unmarshal(cf, &config)
if err != nil {
return SecretLoader{}, err
}
return NewClientWithConfig(config)
}
// Login to the vault server using the given auth token
func Login(cf Config) (string, error) {
loginRequest, err := buildLoginRequest(cf)
if err != nil {
return "", err
}
// Enable SSL connection
tlsConfig := api.TLSConfig{cf.TLSConfig.CACert,
cf.TLSConfig.CAPath,
cf.TLSConfig.ClientCert,
cf.TLSConfig.ClientKey,
cf.TLSConfig.TLSServerName,
cf.TLSConfig.Insecure}
// vault client config
config := api.Config{Address: cf.Address}
config.ConfigureTLS(&tlsConfig)
client, err := api.NewClient(&config)
if err != nil {
return "", err
}
// Attempt login
request := client.NewRequest(http.MethodPost, loginRequest.Endpoint)
request.Body = bytes.NewReader(loginRequest.Body)
response, err := client.RawRequest(request)
if err != nil {
Error.Printf("Failed to login to vault using %s auth method", cf.AuthMethod)
return "", err
}
if response.StatusCode != http.StatusOK {
Error.Printf("Received error status %d", response.StatusCode)
return "", errors.New(fmt.Sprintf("Received error status %d", response.StatusCode))
}
defer response.Body.Close()
// read all the bytes
jwt, err := ioutil.ReadAll(response.Body)
if err != nil {
Error.Println("Failed to read the login response")
return "", err
}
var result map[string]interface{}
if err := json.Unmarshal([]byte(string(jwt)), &result); err != nil {
Error.Println("Failed to unmarshall the login response")
return "", err
}
return result[AUTH].(map[string]interface{})[ClientToken].(string), nil
}
// ReadSecret form the vault repository for given key. If the secret is not present this functions returns an empty string
func (client *SecretLoader) ReadSecret(key string) string {
Info.Printf("Reading secret for a given key: %s", key)
data, ok := client.data["data"].(map[string]interface{})
if ok {
if val := data[key]; val != nil {
return val.(string)
}
return ""
}
if val, ok := client.data[key]; ok {
return val.(string)
}
return ""
}
// For a given auth method the login endpoint is returned
func buildLoginRequest(cf Config) (LoginRequest, error) {
switch cf.AuthMethod {
case KubernetesAuth:
token, err := ioutil.ReadFile(cf.Token)
body, err := json.Marshal(KubeAuthBody{Role: cf.Role, Jwt: string(token)})
return LoginRequest{Body: body, Endpoint: "/v1/auth/kubernetes/login"}, err
case AppRoleAuth:
body, err := json.Marshal(AppRoleAuthBody{SecretID: cf.SecretId, RoleID: cf.RoleId})
return LoginRequest{Body: body, Endpoint: "/v1/auth/approle/login"}, err
default:
return LoginRequest{}, errors.New(
fmt.Sprintf("Only the following auth method are supported:%s,%s", KubernetesAuth, AppRoleAuth))
}
}
// Load all the secrets into a Global map
func loadAllSecrets(token string, cf Config) (map[string]interface{}, error) {
Info.Printf("Loading secrets from the path: %s", cf.SecretPath)
client, err := api.NewClient(&api.Config{Address: cf.Address})
client.SetToken(token)
// Read all the secrets
secret, err := client.Logical().Read(cf.SecretPath)
if err != nil || secret == nil {
Error.Printf("Failed to load the secrets from the given path: %s", cf.SecretPath)
return nil, err
}
return secret.Data, nil
}