-
Notifications
You must be signed in to change notification settings - Fork 208
/
refresher.go
292 lines (235 loc) · 6.94 KB
/
refresher.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
package vault
import (
"context"
"fmt"
"sync"
"time"
"github.com/go-kit/log"
"github.com/grafana/alloy/internal/component"
"github.com/grafana/alloy/internal/runtime/logging/level"
vault "github.com/hashicorp/vault/api"
"github.com/prometheus/client_golang/prometheus"
)
const tokenManagerInitializeTimeout = time.Minute
type getTokenFunc func(ctx context.Context, client *vault.Client) (*vault.Secret, error)
// A tokenManager retrieves and manages the lifecycle of tokens. tokenManager,
// when running, will renew tokens before expiry, and will retrieve new tokens
// once expired tokens can no longer be renewed.
type tokenManager struct {
log log.Logger
refreshTicker *ticker
getter getTokenFunc
onStateChange chan struct{} // Written to when cli or token changes.
readCounter prometheus.Counter
refreshCounter prometheus.Counter
mut sync.RWMutex
cli *vault.Client
token *vault.Secret
healthMut sync.RWMutex
health component.Health
debugMut sync.RWMutex
debugInfo secretInfo
}
type tokenManagerOptions struct {
Log log.Logger
Getter getTokenFunc
ReadCounter, RefreshCounter prometheus.Counter
Client *vault.Client
RefreshInterval time.Duration
}
// newTokenManager creates a new, unstarted tokenManager. tokenManager will
// retrieve the initial token from getter.
func newTokenManager(opts tokenManagerOptions) (*tokenManager, error) {
ctx, cancel := context.WithTimeout(context.Background(), tokenManagerInitializeTimeout)
defer cancel()
tm := &tokenManager{
log: opts.Log,
refreshTicker: newTicker(opts.RefreshInterval),
getter: opts.Getter,
onStateChange: make(chan struct{}, 1),
readCounter: opts.ReadCounter,
refreshCounter: opts.RefreshCounter,
cli: opts.Client,
}
if err := tm.updateToken(ctx); err != nil {
return nil, fmt.Errorf("failed to get token: %w", err)
}
return tm, nil
}
// updateToken attempts to update the token, logging an error if getting the
// token failed.
func (tm *tokenManager) updateToken(ctx context.Context) (err error) {
defer func() {
if err != nil {
tm.updateHealth(component.Health{
Health: component.HealthTypeUnhealthy,
Message: fmt.Sprintf("failed to retrieve token: %s", err),
UpdateTime: time.Now(),
})
} else {
tm.updateHealth(component.Health{
Health: component.HealthTypeHealthy,
Message: "retrieved token",
UpdateTime: time.Now(),
})
}
tm.updateDebugInfo(time.Now())
}()
tm.mut.Lock()
defer tm.mut.Unlock()
token, err := tm.getter(ctx, tm.cli)
if err != nil {
level.Error(tm.log).Log("msg", "failed to get token", "err", err)
return err
}
tm.readCounter.Inc()
tm.token = token
select {
case tm.onStateChange <- struct{}{}:
default:
}
return nil
}
// Run runs the tokenManager, blocking until the provided context is canceled.
func (tm *tokenManager) Run(ctx context.Context) {
var cancelLifecycleWatcher context.CancelFunc
defer func() {
if cancelLifecycleWatcher != nil {
cancelLifecycleWatcher()
}
}()
for {
select {
case <-ctx.Done():
return
case <-tm.refreshTicker.Chan():
level.Info(tm.log).Log("msg", "refreshing token")
// Error is handled via setting health and debug info.
_ = tm.updateToken(ctx)
case <-tm.onStateChange:
if cancelLifecycleWatcher != nil {
cancelLifecycleWatcher()
}
ctx, cancel := context.WithCancel(ctx)
cancelLifecycleWatcher = cancel
tm.updateLifecycleWatcher(ctx)
}
}
}
func (tm *tokenManager) updateHealth(h component.Health) {
tm.healthMut.Lock()
defer tm.healthMut.Unlock()
tm.health = h
}
func (tm *tokenManager) updateDebugInfo(updateTime time.Time) {
tm.mut.RLock()
token := tm.token
tm.mut.RUnlock()
tm.debugMut.Lock()
defer tm.debugMut.Unlock()
tm.debugInfo = getSecretInfo(token, updateTime)
}
func (tm *tokenManager) updateLifecycleWatcher(ctx context.Context) {
tm.mut.RLock()
defer tm.mut.RUnlock()
if !needsLifecycleWatcher(tm.token) {
return
}
lw, err := tm.cli.NewLifetimeWatcher(&vault.LifetimeWatcherInput{
Secret: tm.token,
RenewBehavior: vault.RenewBehaviorIgnoreErrors,
})
if err != nil {
level.Error(tm.log).Log("msg", "failed to create lifetime watcher, lease will not renew automatically", "err", err)
return
}
go lw.Start()
go func() {
for {
select {
case <-ctx.Done():
lw.Stop()
return
case <-lw.DoneCh():
if ctx.Err() != nil {
return
}
// Error is logged as health and debug info.
_ = tm.updateToken(ctx)
case output := <-lw.RenewCh():
tm.refreshCounter.Inc()
level.Debug(tm.log).Log("msg", "token has renewed")
tm.updateDebugInfo(output.RenewedAt)
}
}
}()
}
// needsLifecycleWatcher determines if a secret needs a lifecycle watcher.
// Secrets only need a lifecycle watcher if they are renewable or have a lease
// duration.
func needsLifecycleWatcher(secret *vault.Secret) bool {
if secret == nil {
return false
}
if secret.Auth != nil {
return secret.Auth.Renewable || secret.Auth.LeaseDuration > 0
}
return secret.Renewable || secret.LeaseDuration > 0
}
// SetClient updates the client associated with the tokenManager. This will
// force a new retrieval of the token.
func (tm *tokenManager) SetClient(cli *vault.Client) {
tm.mut.Lock()
tm.cli = cli
tm.mut.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), tokenManagerInitializeTimeout)
defer cancel()
// Error is handled via setting health and debug info.
_ = tm.updateToken(ctx)
}
// SetRefreshInterval sets a forced refresh interval, separate from automatic
// renewal based on the token lease.
func (tm *tokenManager) SetRefreshInterval(interval time.Duration) {
tm.refreshTicker.Reset(interval)
}
// CurrentHealth returns the health of the tokenManager.
func (tm *tokenManager) CurrentHealth() component.Health {
tm.healthMut.RLock()
defer tm.healthMut.RUnlock()
return tm.health
}
// DebugInfo returns the current DebugInfo for the tokenManager.
func (tm *tokenManager) DebugInfo() secretInfo {
tm.debugMut.RLock()
defer tm.debugMut.RUnlock()
return tm.debugInfo
}
type secretInfo struct {
LatestRequestID string `alloy:"latest_request_id,attr"`
LastUpdateTime time.Time `alloy:"last_update_time,attr"`
SecretExpireTime time.Time `alloy:"secret_expire_time,attr"`
Renewable bool `alloy:"renewable,attr"`
Warnings []string `alloy:"warnings,attr"`
}
func getSecretInfo(secret *vault.Secret, updateTime time.Time) secretInfo {
if secret == nil {
return secretInfo{
LastUpdateTime: updateTime,
Warnings: []string{"no secret necessary for configured auth mechanism"},
}
}
return secretInfo{
LatestRequestID: secret.RequestID,
LastUpdateTime: updateTime,
SecretExpireTime: secretExpireTime(secret),
Renewable: secret.Renewable,
Warnings: secret.Warnings,
}
}
func secretExpireTime(secret *vault.Secret) time.Time {
ttl, err := secret.TokenTTL()
if err != nil || ttl == 0 {
return time.Time{}
}
return time.Now().UTC().Add(ttl)
}