-
Notifications
You must be signed in to change notification settings - Fork 4
/
tlsutil.go
89 lines (77 loc) · 1.93 KB
/
tlsutil.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
package main
import (
"crypto/tls"
"log"
"sync"
"gopkg.in/fsnotify.v1"
)
// KeypairReloader structs holds cert path and certs
type KeypairReloader struct {
certMu sync.RWMutex
cert *tls.Certificate
certPath string
keyPath string
}
// NewKeypairReloader will load certs on first run and trigger a goroutine for fsnotify watcher
func NewKeypairReloader(certPath, keyPath string) (*KeypairReloader, error) {
result := &KeypairReloader{
certPath: certPath,
keyPath: keyPath,
}
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
return nil, err
}
result.cert = &cert
// creates a new file watcher
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
defer func() {
if err != nil {
watcher.Close()
}
}()
if err := watcher.Add("/etc/webhook/certs"); err != nil {
return nil, err
}
go func() {
for {
select {
// watch for events
case event := <-watcher.Events:
// fsnotify.create events will tell us if there are new certs
if event.Op&fsnotify.Create == fsnotify.Create {
log.Printf("Reloading certs")
if err := result.reload(); err != nil {
log.Printf("Could not load new certs: %v", err)
}
}
// watch for errors
case err := <-watcher.Errors:
log.Print("error", err)
}
}
}()
return result, nil
}
// reload loads updated cert and key whenever they are updated
func (kpr *KeypairReloader) reload() error {
newCert, err := tls.LoadX509KeyPair(kpr.certPath, kpr.keyPath)
if err != nil {
return err
}
kpr.certMu.Lock()
defer kpr.certMu.Unlock()
kpr.cert = &newCert
return nil
}
// GetCertificateFunc will return function which will be used as tls.Config.GetCertificate
func (kpr *KeypairReloader) GetCertificateFunc() func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
return func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
kpr.certMu.RLock()
defer kpr.certMu.RUnlock()
return kpr.cert, nil
}
}