-
Notifications
You must be signed in to change notification settings - Fork 47
/
cert_file_watcher.go
223 lines (192 loc) · 5.68 KB
/
cert_file_watcher.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
/*
Copyright (c) 2021 - Present. Blend Labs, Inc. All rights reserved
Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
package certutil
import (
"crypto/tls"
"os"
"sync"
"time"
"github.com/blend/go-sdk/async"
"github.com/blend/go-sdk/ex"
)
// Error constants.
const (
ErrTLSPathsUnset ex.Class = "tls cert or key path unset; cannot continue"
)
// NewCertFileWatcher creates a new CertReloader object with a reload delay
func NewCertFileWatcher(certPath, keyPath string, opts ...CertFileWatcherOption) (*CertFileWatcher, error) {
if certPath == "" || keyPath == "" {
return nil, ex.New(ErrTLSPathsUnset)
}
cw := &CertFileWatcher{
latch: async.NewLatch(),
keyPair: KeyPair{
CertPath: certPath,
KeyPath: keyPath,
},
}
for _, opt := range opts {
if err := opt(cw); err != nil {
return nil, err
}
}
cert, err := tls.LoadX509KeyPair(cw.keyPair.CertPath, cw.keyPair.KeyPath)
if err != nil {
return nil, err
}
cw.certificate = &cert
return cw, nil
}
// CertFileWatcherOption is an option for a cert watcher.
type CertFileWatcherOption func(*CertFileWatcher) error
// OptCertFileWatcherOnReload sets the on reload handler.
// If you need to capture *every* reload of the cert, including the initial one in the constructor
// you must use this option.
func OptCertFileWatcherOnReload(handler func(*CertFileWatcher, error)) CertFileWatcherOption {
return func(cfw *CertFileWatcher) error {
cfw.onReload = handler
return nil
}
}
// OptCertFileWatcherNotifyReload sets the notify reload channel.
func OptCertFileWatcherNotifyReload(notifyReload chan struct{}) CertFileWatcherOption {
return func(cfw *CertFileWatcher) error {
cfw.notifyReload = notifyReload
return nil
}
}
// OptCertFileWatcherPollInterval sets the poll interval .
func OptCertFileWatcherPollInterval(d time.Duration) CertFileWatcherOption {
return func(cfw *CertFileWatcher) error {
cfw.pollInterval = d
return nil
}
}
// CertFileWatcher reloads a cert key pair when there is a change, e.g. cert renewal
type CertFileWatcher struct {
latch *async.Latch
certificateMu sync.RWMutex
certificate *tls.Certificate
keyPair KeyPair
pollInterval time.Duration
notifyReload chan struct{}
onReload func(*CertFileWatcher, error)
}
// CertPath returns the cert path.
func (cw *CertFileWatcher) CertPath() string { return cw.keyPair.CertPath }
// KeyPath returns the cert path.
func (cw *CertFileWatcher) KeyPath() string { return cw.keyPair.KeyPath }
// PollIntervalOrDefault returns the polling interval or a default.
func (cw *CertFileWatcher) PollIntervalOrDefault() time.Duration {
if cw.pollInterval > 0 {
return cw.pollInterval
}
return 500 * time.Millisecond
}
// Reload forces the reload of the underlying certificate.
func (cw *CertFileWatcher) Reload() (err error) {
defer func() {
if cw.notifyReload != nil {
cw.notifyReload <- struct{}{}
}
if cw.onReload != nil {
cw.onReload(cw, err)
}
}()
cert, loadErr := tls.LoadX509KeyPair(cw.keyPair.CertPath, cw.keyPair.KeyPath)
if loadErr != nil {
err = ex.New(loadErr)
return
}
cw.certificateMu.Lock()
cw.certificate = &cert
cw.certificateMu.Unlock()
return
}
// Certificate gets the underlying certificate, it blocks when the `cert` field is being updated
func (cw *CertFileWatcher) Certificate() *tls.Certificate {
cw.certificateMu.RLock()
defer cw.certificateMu.RUnlock()
return cw.certificate
}
// GetCertificate gets the underlying certificate in the form that tls config expects.
func (cw *CertFileWatcher) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
cw.certificateMu.RLock()
defer cw.certificateMu.RUnlock()
return cw.certificate, nil
}
// IsStarted returns if the underlying latch is started.
func (cw *CertFileWatcher) IsStarted() bool { return cw.latch.IsStarted() }
// IsStopped returns if the underlying latch is stopped.
func (cw *CertFileWatcher) IsStopped() bool { return cw.latch.IsStopped() }
// NotifyStarted returns the notify started channel.
func (cw *CertFileWatcher) NotifyStarted() <-chan struct{} {
return cw.latch.NotifyStarted()
}
// NotifyStopped returns the notify stopped channel.
func (cw *CertFileWatcher) NotifyStopped() <-chan struct{} {
return cw.latch.NotifyStopped()
}
// NotifyReload the notify reload channel.
//
// You must supply this channel as an option in the constructor.
func (cw *CertFileWatcher) NotifyReload() <-chan struct{} {
return cw.notifyReload
}
// Start watches the cert and triggers a reload on change
func (cw *CertFileWatcher) Start() error {
cw.latch.Starting()
certLastMod, keyLastMod, err := cw.keyPairLastModified()
if err != nil {
cw.latch.Stopped()
return err
}
ticker := time.NewTicker(cw.PollIntervalOrDefault())
defer ticker.Stop()
cw.latch.Started()
var certMod, keyMod time.Time
for {
select {
case <-ticker.C:
certMod, keyMod, err = cw.keyPairLastModified()
if err != nil {
return err
}
// wait for both to update
if keyMod.After(keyLastMod) && certMod.After(certLastMod) {
if err = cw.Reload(); err == nil {
keyLastMod = keyMod
certLastMod = certMod
}
}
case <-cw.latch.NotifyStopping():
cw.latch.Stopped()
return nil
}
}
}
// Stop stops the watcher.
func (cw *CertFileWatcher) Stop() error {
if !cw.latch.CanStop() {
return async.ErrCannotStop
}
cw.latch.WaitStopped()
cw.latch.Reset()
return nil
}
func (cw *CertFileWatcher) keyPairLastModified() (cert time.Time, key time.Time, err error) {
var certStat, keyStat os.FileInfo
certStat, err = os.Stat(cw.keyPair.CertPath)
if err != nil {
return
}
keyStat, err = os.Stat(cw.keyPair.KeyPath)
if err != nil {
return
}
cert = certStat.ModTime()
key = keyStat.ModTime()
return
}