-
Notifications
You must be signed in to change notification settings - Fork 1
/
certificate.go
111 lines (94 loc) · 2.52 KB
/
certificate.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
// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Gardener contributors
//
// SPDX-License-Identifier: Apache-2.0
package dynamiccert
import (
"crypto/tls"
"slices"
"sync"
"time"
"github.com/go-logr/logr"
)
// DynamicCertificate implements [tls.Config.GetCertificate].
// It returns a TLS certificate and refreshes if needed.
type DynamicCertificate struct {
certFile string
keyFile string
interval time.Duration
certificate *tls.Certificate
log logr.Logger
lock sync.RWMutex
}
// New returns a new instance of [DynamicCertificate].
func New(certFile, keyFile string, opts ...Option) (*DynamicCertificate, error) {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
dynamicCert := &DynamicCertificate{
certFile: certFile,
keyFile: keyFile,
certificate: &cert,
interval: time.Minute,
log: logr.Discard(),
}
for _, opt := range opts {
opt(dynamicCert)
}
go func() {
ticker := time.NewTicker(dynamicCert.interval)
for range ticker.C {
if err := dynamicCert.reloadCert(); err != nil {
dynamicCert.log.Error(err, "Failed to reload certificates")
}
}
}()
return dynamicCert, nil
}
func (dc *DynamicCertificate) reloadCert() error {
cert, err := tls.LoadX509KeyPair(dc.certFile, dc.keyFile)
if err != nil {
return err
}
dc.lock.Lock()
defer dc.lock.Unlock()
if areEqual(cert.Certificate, dc.certificate.Certificate) {
// do not renew the certificate if the current equals the new
return nil
}
dc.certificate = &cert
dc.log.Info("Certificate was reloaded")
return nil
}
func areEqual(cert1 [][]byte, cert2 [][]byte) bool {
if len(cert1) != len(cert2) {
return false
}
for i := range cert1 {
if !slices.Equal(cert1[i], cert2[i]) {
return false
}
}
return true
}
// GetCertificate returns the current loaded certificate.
func (dc *DynamicCertificate) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
dc.lock.RLock()
defer dc.lock.RUnlock()
return dc.certificate, nil
}
// Option can be used to configure [DynamicCertificate].
type Option func(*DynamicCertificate)
// WithRefreshInterval sets the interval that will be used
// to periodically check if the TLS certificate should be refreshed.
func WithRefreshInterval(interval time.Duration) Option {
return func(dc *DynamicCertificate) {
dc.interval = interval
}
}
// WithLogger sets the logger for [DynamicCertificate].
func WithLogger(log logr.Logger) Option {
return func(dc *DynamicCertificate) {
dc.log = log
}
}