forked from kubernetes/autoscaler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcerts.go
More file actions
160 lines (146 loc) · 4.64 KB
/
certs.go
File metadata and controls
160 lines (146 loc) · 4.64 KB
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
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"context"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"os"
"sync"
"github.com/fsnotify/fsnotify"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
admissionregistrationv1 "k8s.io/client-go/kubernetes/typed/admissionregistration/v1"
"k8s.io/klog/v2"
)
func readFile(filePath string) []byte {
res, err := os.ReadFile(filePath)
if err != nil {
klog.ErrorS(err, "Error reading certificate file", "file", filePath)
return nil
}
klog.V(3).InfoS("Successfully read bytes from file", "bytes", len(res), "file", filePath)
return res
}
type certReloader struct {
tlsCertPath string
tlsKeyPath string
clientCaPath string
cert *tls.Certificate
mu sync.RWMutex
mutatingWebhookClient admissionregistrationv1.MutatingWebhookConfigurationInterface
}
func (cr *certReloader) start(stop <-chan struct{}) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
if err = watcher.Add(cr.tlsCertPath); err != nil {
return err
}
if err = watcher.Add(cr.tlsKeyPath); err != nil {
return err
}
// we watch the CA file ony when registerWebhook is enabled
if cr.mutatingWebhookClient != nil {
if err = watcher.Add(cr.clientCaPath); err != nil {
return err
}
}
go func() {
defer watcher.Close() // nolint:errcheck
for {
select {
case event := <-watcher.Events:
// we need to watch "Remove" events because Kubernetes uses symbolic links to point to ConfigMaps/Secrets volumes
if !event.Has(fsnotify.Remove) && !event.Has(fsnotify.Create) && !event.Has(fsnotify.Write) {
continue
}
switch event.Name {
case cr.tlsCertPath, cr.tlsKeyPath:
klog.V(2).InfoS("New certificate found, reloading")
if err := cr.load(); err != nil {
klog.ErrorS(err, "Failed to reload certificate")
}
case cr.clientCaPath:
if err := cr.reloadWebhookCA(); err != nil {
klog.ErrorS(err, "Failed to reload client CA")
}
default:
continue
}
// watches get removed along with the symlinks, so we need to add them back
if event.Has(fsnotify.Remove) {
if err := watcher.Add(event.Name); err != nil {
klog.ErrorS(err, "Failed to add watcher for file", "filename", event.Name)
}
}
case err := <-watcher.Errors:
klog.Warningf("Error watching certificate files: %s", err)
case <-stop:
return
}
}
}()
return nil
}
func (cr *certReloader) load() error {
cert, err := tls.LoadX509KeyPair(cr.tlsCertPath, cr.tlsKeyPath)
if err != nil {
return err
}
cr.mu.Lock()
defer cr.mu.Unlock()
cr.cert = &cert
return nil
}
func (cr *certReloader) reloadWebhookCA() error {
client := cr.mutatingWebhookClient
if client == nil {
// this should never happen as we don't watch the file if mutatingWebhookClient is nil
return errors.New("webhook client is not set")
}
webhook, err := client.Get(context.TODO(), webhookConfigName, metav1.GetOptions{})
if err != nil {
return err
}
if webhook == nil {
return errors.New("webhook not found")
}
if len(webhook.Webhooks) == 0 {
return errors.New("webhook configuration has no webhooks")
}
currentBundle := webhook.Webhooks[0].ClientConfig.CABundle[:]
base64CurrentBundle := base64.StdEncoding.EncodeToString(currentBundle)
newBundle := readFile(cr.clientCaPath)
base64NewBundle := base64.StdEncoding.EncodeToString(newBundle)
// make sure clientCA actually changed
if base64CurrentBundle == base64NewBundle {
klog.V(2).InfoS("Client CA did not change, skipping patch")
return nil
}
klog.V(2).InfoS("New client CA found, reloading and patching webhook")
patch := fmt.Appendf(nil, `{"webhooks":[{"name":"%s","clientConfig":{"caBundle":"%s"}}]}`, webhookName, base64NewBundle)
_, err = client.Patch(context.TODO(), webhookConfigName, types.StrategicMergePatchType, patch, metav1.PatchOptions{})
if err == nil {
klog.V(2).InfoS("Successfully patched webhook with new client CA")
}
return err
}
func (cr *certReloader) getCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
cr.mu.RLock()
defer cr.mu.RUnlock()
return cr.cert, nil
}