-
Notifications
You must be signed in to change notification settings - Fork 0
/
vault.go
272 lines (229 loc) · 5.7 KB
/
vault.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
package vaultenv
import (
"context"
"io"
"log"
"os"
"os/user"
"path"
"path/filepath"
"strings"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/api/auth/gcp"
"github.com/hashicorp/vault/api/auth/kubernetes"
"github.com/james-lawrence/vaultenv/internal/x/errorsx"
"github.com/james-lawrence/vaultenv/internal/x/stringsx"
"github.com/pkg/errors"
)
// VaultDefaultTokenPath returns the path to the default location of the vault token.
func vaultDefaultTokenPath() string {
var (
err error
u *user.User
)
if u, err = user.Current(); err != nil {
log.Println("failed to lookup the current user, unable to generate default token path", err)
return ""
}
return filepath.Join(u.HomeDir, ".vault-token")
}
func DetectAuth(method string) api.AuthMethod {
if method == "" {
method = os.Getenv("VAULTENV_AUTH_METHOD")
}
switch method {
case "k8s":
a, err := kubernetes.NewKubernetesAuth(
os.Getenv("VAULTENV_AUTH_ROLE"),
)
if err == nil {
return a
}
log.Println("failed to authenticate with kubernetes", err)
case "gcp-gce":
a, err := gcp.NewGCPAuth(
os.Getenv("VAULTENV_AUTH_ROLE"),
gcp.WithGCEAuth(),
)
if err == nil {
return a
}
log.Println("failed to authenticate with gcp-gce", err)
case "gcp-iam":
a, err := gcp.NewGCPAuth(
os.Getenv("VAULTENV_AUTH_ROLE"),
gcp.WithIAMAuth(
os.Getenv("VAULTENV_AUTH_GCP_IAM_SERVICE_ACCOUNT"),
),
)
if err == nil {
return a
}
log.Println("failed to authenticate with gcp-iam", err)
default:
}
return nil
}
// NewVault configures vault with defaults.
func NewVault(auth api.AuthMethod) (v Vault, err error) {
var (
client *api.Client
config *api.Config
)
if config = api.DefaultConfig(); config.Error != nil {
return v, errors.WithStack(config.Error)
}
if client, err = api.NewClient(config); err != nil {
return v, errors.WithStack(err)
}
if auth == nil {
client.SetToken(stringsx.DefaultIfBlank(client.Token(), readTokenFile(vaultDefaultTokenPath())))
} else {
if _, err = client.Auth().Login(context.Background(), auth); err != nil {
return v, errors.WithStack(err)
}
}
return Vault{
client: client,
}, nil
}
// Vault api retrieves latest secrets from the vault
type Vault struct {
client *api.Client
}
// Read
func (t Vault) Read(path string) (err error) {
var (
secret *api.Secret
ok bool
opaqueData interface{}
data map[string]interface{}
)
mountPath, v2, err := isKVv2(path, t.client)
if err != nil {
return err
}
if v2 {
path = addPrefixToVKVPath(path, mountPath, "data")
}
if secret, err = kvReadRequest(t.client, path); err != nil {
return err
}
if opaqueData, ok = secret.Data["data"]; !ok {
return errorsx.String("missing secret")
}
if data, ok = opaqueData.(map[string]interface{}); !ok {
return errorsx.String("invalid secret data")
}
for k, v := range data {
var (
value string
)
if value, ok = v.(string); !ok {
return errorsx.String("values must be strings")
}
if err = os.Setenv(k, value); err != nil {
return err
}
}
return nil
}
func readTokenFile(path string) string {
var (
err error
raw []byte
)
if raw, err = os.ReadFile(path); err != nil {
log.Println("failed to read vault token from file", path, err)
return ""
}
return string(raw)
}
func kvReadRequest(client *api.Client, path string) (*api.Secret, error) {
r := client.NewRequest("GET", "/v1/"+path)
resp, err := client.RawRequest(r)
if resp != nil {
defer resp.Body.Close()
}
if resp != nil && resp.StatusCode == 404 {
secret, parseErr := api.ParseSecret(resp.Body)
switch parseErr {
case nil:
case io.EOF:
return nil, nil
default:
return nil, err
}
if secret != nil && (len(secret.Warnings) > 0 || len(secret.Data) > 0) {
return secret, nil
}
return nil, nil
}
if err != nil {
return nil, err
}
return api.ParseSecret(resp.Body)
}
func isKVv2(path string, client *api.Client) (string, bool, error) {
mountPath, version, err := kvPreflightVersionRequest(client, path)
if err != nil {
return "", false, err
}
return mountPath, version == 2, nil
}
func addPrefixToVKVPath(p, mountPath, apiPrefix string) string {
switch {
case p == mountPath, p == strings.TrimSuffix(mountPath, "/"):
return path.Join(mountPath, apiPrefix)
default:
p = strings.TrimPrefix(p, mountPath)
return path.Join(mountPath, apiPrefix, p)
}
}
func kvPreflightVersionRequest(client *api.Client, path string) (string, int, error) {
// We don't want to use a wrapping call here so save any custom value and
// restore after
currentWrappingLookupFunc := client.CurrentWrappingLookupFunc()
client.SetWrappingLookupFunc(nil)
defer client.SetWrappingLookupFunc(currentWrappingLookupFunc)
currentOutputCurlString := client.OutputCurlString()
client.SetOutputCurlString(false)
defer client.SetOutputCurlString(currentOutputCurlString)
r := client.NewRequest("GET", "/v1/sys/internal/ui/mounts/"+path)
resp, err := client.RawRequest(r)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
// If we get a 404 we are using an older version of vault, default to
// version 1
if resp != nil && resp.StatusCode == 404 {
return "", 1, nil
}
return "", 0, err
}
secret, err := api.ParseSecret(resp.Body)
if err != nil {
return "", 0, err
}
var mountPath string
if mountPathRaw, ok := secret.Data["path"]; ok {
mountPath = mountPathRaw.(string)
}
options := secret.Data["options"]
if options == nil {
return mountPath, 1, nil
}
versionRaw := options.(map[string]interface{})["version"]
if versionRaw == nil {
return mountPath, 1, nil
}
version := versionRaw.(string)
switch version {
case "", "1":
return mountPath, 1, nil
case "2":
return mountPath, 2, nil
}
return mountPath, 1, nil
}