-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls-cache.go
96 lines (81 loc) · 1.76 KB
/
tls-cache.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
package fleet
import (
"crypto"
"crypto/tls"
"log"
"sync"
"time"
)
type crtCache struct {
a *Agent
k string
lk sync.Mutex
t time.Time
crt *tls.Certificate
err error
}
func (c *crtCache) GetClientCertificate(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
crt, err := c.GetCertificate(nil)
if err != nil {
// error happened, but we don't care, let's just try without certificate.
// Go documentation: GetClientCertificate must return non-nil
return &tls.Certificate{}, nil
}
return crt, nil
}
func (c *crtCache) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
if time.Since(c.t) < time.Hour*24 {
return c.crt, c.err
}
c.lk.Lock()
defer c.lk.Unlock()
if time.Since(c.t) < time.Hour*24 {
return c.crt, c.err
}
c.t = time.Now()
c.crt, c.err = c.loadCert()
if c.err != nil {
log.Printf("[tls] Failed to fetch %s certificate: %s", c.k, c.err)
}
return c.crt, c.err
}
func (c *crtCache) PrivateKey() (crypto.PrivateKey, error) {
if time.Since(c.t) < time.Hour*24 {
if c.err != nil {
return nil, c.err
}
return c.crt.PrivateKey, nil
}
c.lk.Lock()
defer c.lk.Unlock()
if time.Since(c.t) < time.Hour*24 {
if c.err != nil {
return nil, c.err
}
return c.crt.PrivateKey, nil
}
c.t = time.Now()
c.crt, c.err = c.loadCert()
if c.err != nil {
log.Printf("[tls] Failed to fetch %s certificate: %s", c.k, c.err)
}
if c.err != nil {
return nil, c.err
}
return c.crt.PrivateKey, nil
}
func (c *crtCache) loadCert() (*tls.Certificate, error) {
crt, err := c.a.dbFleetLoad(c.k + ":crt")
if err != nil {
return nil, err
}
key, err := c.a.dbFleetGet(c.k + ":key")
if err != nil {
return nil, err
}
res, err := tls.X509KeyPair(crt, key)
if err != nil {
return nil, err
}
return &res, nil
}