-
Notifications
You must be signed in to change notification settings - Fork 781
/
vault_common.go
375 lines (320 loc) · 10.3 KB
/
vault_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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package dependency
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"sync"
"time"
"github.com/hashicorp/vault/api"
)
var (
// VaultDefaultLeaseDuration is the default lease duration in seconds.
VaultDefaultLeaseDuration time.Duration
onceVaultDefaultLeaseDuration sync.Once
VaultLeaseRenewalThreshold float64
onceVaultLeaseRenewalThreshold sync.Once
)
// Secret is the structure returned for every secret within Vault.
type Secret struct {
// The request ID that generated this response
RequestID string
LeaseID string
LeaseDuration int
Renewable bool
// Data is the actual contents of the secret. The format of the data
// is arbitrary and up to the secret backend.
Data map[string]interface{}
// Warnings contains any warnings related to the operation. These
// are not issues that caused the command to fail, but that the
// client should be aware of.
Warnings []string
// Auth, if non-nil, means that there was authentication information
// attached to this response.
Auth *SecretAuth
// WrapInfo, if non-nil, means that the initial response was wrapped in the
// cubbyhole of the given token (which has a TTL of the given number of
// seconds)
WrapInfo *SecretWrapInfo
}
// SecretAuth is the structure containing auth information if we have it.
type SecretAuth struct {
ClientToken string
Accessor string
Policies []string
Metadata map[string]string
LeaseDuration int
Renewable bool
}
// SecretWrapInfo contains wrapping information if we have it. If what is
// contained is an authentication token, the accessor for the token will be
// available in WrappedAccessor.
type SecretWrapInfo struct {
Token string
TTL int
CreationTime time.Time
WrappedAccessor string
}
type renewer interface {
Dependency
stopChan() chan struct{}
secrets() (*Secret, *api.Secret)
}
func renewSecret(clients *ClientSet, d renewer) error {
log.Printf("[TRACE] %s: starting renewer", d)
secret, vaultSecret := d.secrets()
renewer, err := clients.Vault().NewLifetimeWatcher(&api.LifetimeWatcherInput{
Secret: vaultSecret,
RenewBehavior: api.RenewBehaviorErrorOnErrors,
})
if err != nil {
return err
}
go renewer.Renew()
defer renewer.Stop()
for {
select {
case err := <-renewer.DoneCh():
if err != nil {
log.Printf("[WARN] %s: failed to renew: %s", d, err)
}
log.Printf("[WARN] %s: renewer done (maybe the lease expired)", d)
return nil
case renewal := <-renewer.RenewCh():
log.Printf("[TRACE] %s: successfully renewed", d)
printVaultWarnings(d, renewal.Secret.Warnings)
updateSecret(secret, renewal.Secret)
case <-d.stopChan():
return ErrStopped
}
}
}
// leaseCheckWait accepts a secret and returns the recommended amount of
// time to sleep.
func leaseCheckWait(s *Secret) time.Duration {
// Handle whether this is an auth or a regular secret.
base := s.LeaseDuration
if s.Auth != nil && s.Auth.LeaseDuration > 0 {
base = s.Auth.LeaseDuration
}
// Handle if this is a certificate with no lease
if _, ok := s.Data["certificate"]; ok && s.LeaseID == "" {
if expInterface, ok := s.Data["expiration"]; ok {
if expData, err := expInterface.(json.Number).Int64(); err == nil {
base = int(expData - time.Now().Unix())
log.Printf("[DEBUG] Found certificate and set lease duration to %d seconds", base)
}
}
}
// Handle if this is an AppRole secret_id with no lease
if _, ok := s.Data["secret_id"]; ok && s.LeaseID == "" {
if expInterface, ok := s.Data["secret_id_ttl"]; ok {
if ttlData, err := expInterface.(json.Number).Int64(); err == nil && ttlData > 0 {
base = int(ttlData) + 1
log.Printf("[DEBUG] Found approle secret_id and non-zero secret_id_ttl, setting lease duration to %d seconds", base)
}
}
}
// Handle if this is a secret with a rotation period. If this is a rotating secret,
// the rotating secret's TTL will be the duration to sleep before rendering the new secret.
var rotatingSecret bool
if _, ok := s.Data["rotation_period"]; ok && s.LeaseID == "" {
if ttlInterface, ok := s.Data["ttl"]; ok {
if ttlData, err := ttlInterface.(json.Number).Int64(); err == nil {
log.Printf("[DEBUG] Found rotation_period and set lease duration to %d seconds", ttlData)
// Add a second for cushion
base = int(ttlData) + 1
rotatingSecret = true
}
}
}
// Ensure we have a lease duration, since sometimes this can be zero.
if base <= 0 {
base = int(VaultDefaultLeaseDuration.Seconds())
}
// Convert to float seconds.
sleep := float64(time.Duration(base) * time.Second)
if vaultSecretRenewable(s) {
// Renew at 1/3 the remaining lease. This will give us an opportunity to retry
// at least one more time should the first renewal fail.
sleep = sleep / 3.0
// Use some randomness so many clients do not hit Vault simultaneously.
sleep = sleep * (rand.Float64() + 1) / 2.0
} else if !rotatingSecret {
// If the secret doesn't have a rotation period, this is a non-renewable leased
// secret.
// For non-renewable leases set the renew duration to use much of the secret
// lease as possible. Use a stagger over the configured threshold
// fraction of the lease duration so that many clients do not hit
// Vault simultaneously.
finalFraction := VaultLeaseRenewalThreshold + (rand.Float64()-0.5)*0.1
if finalFraction >= 1.0 || finalFraction <= 0.0 {
// If the fraction randomly winds up outside of (0.0-1.0), clamp
// back down to the VaultLeaseRenewalThreshold provided by the user,
// since a) the user picked that value, so they should be
// comfortable with it, and b) it should not skew the staggering too
// much
finalFraction = VaultLeaseRenewalThreshold
}
sleep = sleep * finalFraction
}
return time.Duration(sleep)
}
// printVaultWarnings prints warnings for a given dependency.
func printVaultWarnings(d Dependency, warnings []string) {
for _, w := range warnings {
log.Printf("[WARN] %s: %s", d, w)
}
}
// vaultSecretRenewable determines if the given secret is renewable.
func vaultSecretRenewable(s *Secret) bool {
if s.Auth != nil {
return s.Auth.Renewable
}
return s.Renewable
}
// transformSecret transforms an api secret into our secret. This does not deep
// copy underlying deep data structures, so it's not safe to modify the vault
// secret as that may modify the data in the transformed secret.
func transformSecret(theirs *api.Secret) *Secret {
var ours Secret
updateSecret(&ours, theirs)
return &ours
}
// updateSecret updates our secret with the new data from the api, careful to
// not overwrite missing data. Renewals don't include the original secret, and
// we don't want to delete that data accidentally.
func updateSecret(ours *Secret, theirs *api.Secret) {
if theirs.RequestID != "" {
ours.RequestID = theirs.RequestID
}
if theirs.LeaseID != "" {
ours.LeaseID = theirs.LeaseID
}
if theirs.LeaseDuration != 0 {
ours.LeaseDuration = theirs.LeaseDuration
}
if theirs.Renewable {
ours.Renewable = theirs.Renewable
}
if len(theirs.Data) != 0 {
ours.Data = theirs.Data
}
if len(theirs.Warnings) != 0 {
ours.Warnings = theirs.Warnings
}
if theirs.Auth != nil {
if ours.Auth == nil {
ours.Auth = &SecretAuth{}
}
if theirs.Auth.ClientToken != "" {
ours.Auth.ClientToken = theirs.Auth.ClientToken
}
if theirs.Auth.Accessor != "" {
ours.Auth.Accessor = theirs.Auth.Accessor
}
if len(theirs.Auth.Policies) != 0 {
ours.Auth.Policies = theirs.Auth.Policies
}
if len(theirs.Auth.Metadata) != 0 {
ours.Auth.Metadata = theirs.Auth.Metadata
}
if theirs.Auth.LeaseDuration != 0 {
ours.Auth.LeaseDuration = theirs.Auth.LeaseDuration
}
if theirs.Auth.Renewable {
ours.Auth.Renewable = theirs.Auth.Renewable
}
}
if theirs.WrapInfo != nil {
if ours.WrapInfo == nil {
ours.WrapInfo = &SecretWrapInfo{}
}
if theirs.WrapInfo.Token != "" {
ours.WrapInfo.Token = theirs.WrapInfo.Token
}
if theirs.WrapInfo.TTL != 0 {
ours.WrapInfo.TTL = theirs.WrapInfo.TTL
}
if !theirs.WrapInfo.CreationTime.IsZero() {
ours.WrapInfo.CreationTime = theirs.WrapInfo.CreationTime
}
if theirs.WrapInfo.WrappedAccessor != "" {
ours.WrapInfo.WrappedAccessor = theirs.WrapInfo.WrappedAccessor
}
}
}
func isKVv2(client *api.Client, path string) (string, bool, 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)
resp, err := client.Logical().ReadRaw("sys/internal/ui/mounts/" + path)
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 "", false, nil
}
// anonymous requests may fail to access /sys/internal/ui path
// Vault v1.1.3 returns 500 status code but may return 4XX in future
if client.Token() == "" {
return "", false, nil
}
return "", false, err
}
secret, err := api.ParseSecret(resp.Body)
if err != nil {
return "", false, err
}
if secret == nil {
return "", false, fmt.Errorf("secret at path %s does not exist", path)
}
var mountPath string
if mountPathRaw, ok := secret.Data["path"]; ok {
mountPath = mountPathRaw.(string)
}
var mountType string
if mountTypeRaw, ok := secret.Data["type"]; ok {
mountType = mountTypeRaw.(string)
}
options := secret.Data["options"]
if options == nil {
return mountPath, false, nil
}
versionRaw := options.(map[string]interface{})["version"]
if versionRaw == nil {
return mountPath, false, nil
}
version := versionRaw.(string)
switch version {
case "", "1":
return mountPath, false, nil
case "2":
return mountPath, mountType == "kv", nil
}
return mountPath, false, nil
}
// Make sure to only set VaultDefaultLeaseDuration once
func SetVaultDefaultLeaseDuration(t time.Duration) {
set := func() {
VaultDefaultLeaseDuration = t
}
onceVaultDefaultLeaseDuration.Do(set)
}
// Make sure to only set VaultLeaseRenewalThreshold once
func SetVaultLeaseRenewalThreshold(f float64) {
set := func() {
VaultLeaseRenewalThreshold = f
}
onceVaultLeaseRenewalThreshold.Do(set)
}