-
Notifications
You must be signed in to change notification settings - Fork 543
/
cert_updater.go
69 lines (61 loc) · 1.86 KB
/
cert_updater.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
package filemonitor
import (
"crypto/tls"
"crypto/x509"
"sync"
"github.com/fsnotify/fsnotify"
"github.com/sirupsen/logrus"
)
type certStore struct {
mutex sync.RWMutex
cert *tls.Certificate
tlsCrtPath string
tlsKeyPath string
}
// NewCertStore returns a store for storing the certificate data and the ability to retrieve it safely
func NewCertStore(tlsCrt, tlsKey string) (*certStore, error) {
cert, err := tls.LoadX509KeyPair(tlsCrt, tlsKey)
if err != nil {
return nil, err
}
return &certStore{
mutex: sync.RWMutex{},
cert: &cert,
tlsCrtPath: tlsCrt,
tlsKeyPath: tlsKey,
}, nil
}
// HandleFilesystemUpdate is intended to be used as the OnUpdateFn for a watcher
// and expects the certificate files to be in the same directory.
func (k *certStore) HandleFilesystemUpdate(logger logrus.FieldLogger, event fsnotify.Event) {
switch op := event.Op; op {
case fsnotify.Create:
logger.Debugf("got fs event for %v", event.Name)
if err := k.storeCertificate(k.tlsCrtPath, k.tlsKeyPath); err != nil {
// this can happen if both certificates aren't updated at the same
// time, but it's okay as replacement only occurs with a valid key pair
logger.Debugf("certificates not in sync: %v", err)
} else {
info, err := x509.ParseCertificate(k.cert.Certificate[0])
if err != nil {
logger.Debugf("certificates refreshed, but parsing returned error: %v", err)
} else {
logger.Debugf("certificates refreshed: Subject=%v NotBefore=%v NotAfter=%v", info.Subject, info.NotBefore, info.NotAfter)
}
}
}
}
func (k *certStore) storeCertificate(tlsCrt, tlsKey string) error {
cert, err := tls.LoadX509KeyPair(tlsCrt, tlsKey)
if err == nil {
k.mutex.Lock()
defer k.mutex.Unlock()
k.cert = &cert
}
return err
}
func (k *certStore) GetCertificate() *tls.Certificate {
k.mutex.RLock()
defer k.mutex.RUnlock()
return k.cert
}