/
rotate.go
229 lines (198 loc) · 6.33 KB
/
rotate.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
// Copyright 2023 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package secretbackendrotate
import (
"fmt"
"time"
"github.com/juju/clock"
"github.com/juju/errors"
"github.com/juju/worker/v3"
"github.com/juju/worker/v3/catacomb"
"github.com/juju/juju/core/watcher"
)
// logger is here to stop the desire of creating a package level logger.
// Don't do this, instead use the one passed as manifold config.
type logger interface{}
var _ logger = struct{}{}
// Logger represents the methods used by the worker to log information.
type Logger interface {
Debugf(string, ...interface{})
}
// SecretBackendManagerFacade instances provide a watcher for secret rotation changes.
type SecretBackendManagerFacade interface {
WatchTokenRotationChanges() (watcher.SecretBackendRotateWatcher, error)
RotateBackendTokens(info ...string) error
}
// Config defines the operation of the Worker.
type Config struct {
SecretBackendManagerFacade SecretBackendManagerFacade
Logger Logger
Clock clock.Clock
}
// Validate returns an error if config cannot drive the Worker.
func (config Config) Validate() error {
if config.SecretBackendManagerFacade == nil {
return errors.NotValidf("nil Facade")
}
if config.Clock == nil {
return errors.NotValidf("nil Clock")
}
if config.Logger == nil {
return errors.NotValidf("nil Logger")
}
return nil
}
// NewWorker returns a Secret Backend token rotation Worker backed by config, or an error.
func NewWorker(config Config) (worker.Worker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
w := &Worker{
config: config,
backendInfo: make(map[string]tokenRotateInfo),
}
err := catacomb.Invoke(catacomb.Plan{
Site: &w.catacomb,
Work: w.loop,
})
return w, errors.Trace(err)
}
type tokenRotateInfo struct {
ID string
backendName string
rotateTime time.Time
whenFunc func(rotateTime time.Time) time.Duration
}
func (s tokenRotateInfo) GoString() string {
return fmt.Sprintf("%s token rotation: in %v at %s", s.backendName, s.whenFunc(s.rotateTime), s.rotateTime.Format(time.RFC3339))
}
// Worker fires events when secrets should be rotated.
type Worker struct {
catacomb catacomb.Catacomb
config Config
backendInfo map[string]tokenRotateInfo
timer clock.Timer
nextTrigger time.Time
}
// Kill is defined on worker.Worker.
func (w *Worker) Kill() {
w.catacomb.Kill(nil)
}
// Wait is part of the worker.Worker interface.
func (w *Worker) Wait() error {
return w.catacomb.Wait()
}
func (w *Worker) loop() (err error) {
changes, err := w.config.SecretBackendManagerFacade.WatchTokenRotationChanges()
if err != nil {
return errors.Trace(err)
}
if err := w.catacomb.Add(changes); err != nil {
return errors.Trace(err)
}
for {
var timeout <-chan time.Time
if w.timer != nil {
timeout = w.timer.Chan()
}
select {
case <-w.catacomb.Dying():
return w.catacomb.ErrDying()
case ch, ok := <-changes.Changes():
if !ok {
return errors.New("secret rotation change channel closed")
}
w.handleTokenRotateChanges(ch)
case now := <-timeout:
if err := w.rotate(now); err != nil {
return errors.Annotatef(err, "rotating secret backends")
}
}
}
}
func (w *Worker) rotate(now time.Time) error {
w.config.Logger.Debugf("processing secret backend token rotation at %s", now)
var toRotate []string
for id, info := range w.backendInfo {
w.config.Logger.Debugf("checking %s: rotate at %s... time diff %s", id, info.rotateTime, info.rotateTime.Sub(now))
// A one minute granularity is acceptable for secret rotation.
if info.rotateTime.Truncate(time.Minute).Before(now) {
w.config.Logger.Debugf("rotating token for %s", info.backendName)
toRotate = append(toRotate, id)
// Once backend has been queued for rotation, delete it here since
// it will re-appear via the watcher after the rotation is actually
// performed and the last rotated time is updated.
delete(w.backendInfo, id)
}
}
if err := w.config.SecretBackendManagerFacade.RotateBackendTokens(toRotate...); err != nil {
return errors.Annotatef(err, "cannot rotate secret backend tokens for backend ids %q", toRotate)
}
w.computeNextRotateTime()
return nil
}
func (w *Worker) handleTokenRotateChanges(changes []watcher.SecretBackendRotateChange) {
w.config.Logger.Debugf("got rotate secret changes: %#v", changes)
if len(changes) == 0 {
return
}
for _, ch := range changes {
// Next rotate time of 0 means the rotation has been deleted.
if ch.NextTriggerTime.IsZero() {
w.config.Logger.Debugf("token for %q no longer rotated", ch.Name)
delete(w.backendInfo, ch.ID)
continue
}
w.backendInfo[ch.ID] = tokenRotateInfo{
ID: ch.ID,
backendName: ch.Name,
rotateTime: ch.NextTriggerTime,
whenFunc: func(rotateTime time.Time) time.Duration { return rotateTime.Sub(w.config.Clock.Now()) },
}
}
w.computeNextRotateTime()
}
func (w *Worker) computeNextRotateTime() {
w.config.Logger.Debugf("computing next rotated time for secret backends %#v", w.backendInfo)
if len(w.backendInfo) == 0 {
w.timer = nil
return
}
// Find the minimum (next) rotateTime from all the tokens.
var soonestRotateTime time.Time
for _, info := range w.backendInfo {
if !soonestRotateTime.IsZero() && info.rotateTime.After(soonestRotateTime) {
continue
}
soonestRotateTime = info.rotateTime
}
// There's no need to start or reset the timer if there's no changes to make.
if soonestRotateTime.IsZero() || w.nextTrigger == soonestRotateTime {
return
}
// Account for the worker not running when a secret
// should have been rotated.
now := w.config.Clock.Now()
if soonestRotateTime.Before(now) {
soonestRotateTime = now
}
nextDuration := soonestRotateTime.Sub(now)
w.config.Logger.Debugf("next token will rotate in %v at %s", nextDuration, soonestRotateTime)
w.nextTrigger = soonestRotateTime
if w.timer == nil {
w.timer = w.config.Clock.NewTimer(nextDuration)
} else {
// See the docs on Timer.Reset() that says it isn't safe to call
// on a non-stopped channel, and if it is stopped, you need to check
// if the channel needs to be drained anyway. It isn't safe to drain
// unconditionally in case another goroutine has already noticed,
// but make an attempt.
if !w.timer.Stop() {
select {
case <-w.timer.Chan():
default:
}
}
w.timer.Reset(nextDuration)
}
}