This repository has been archived by the owner on Oct 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
webhook_configuration.go
264 lines (235 loc) · 7.52 KB
/
webhook_configuration.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
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package extension
import (
"context"
"encoding/base64"
"fmt"
"net"
"net/url"
"os"
"path"
"strconv"
"code.cloudfoundry.org/quarks-utils/pkg/credsgen"
"github.com/pkg/errors"
"github.com/spf13/afero"
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
machinerytypes "k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"code.cloudfoundry.org/eirinix/util/ctxlog"
)
// WebhookConfig generates certificates and the configuration for the webhook server
type WebhookConfig struct {
ConfigName string
CertDir string
Certificate []byte
Key []byte
CaCertificate []byte
CaKey []byte
serviceName, webhookNamespace string
setupCertificateName string
client client.Client
config *Config
generator credsgen.Generator
}
// NewWebhookConfig returns a new WebhookConfig
func NewWebhookConfig(c client.Client, config *Config, generator credsgen.Generator, configName string, setupCertificateName string, serviceName string, webhookNamespace string) *WebhookConfig {
return &WebhookConfig{
ConfigName: configName,
CertDir: path.Join(os.TempDir(), setupCertificateName),
client: c,
config: config,
generator: generator,
serviceName: serviceName,
webhookNamespace: webhookNamespace,
setupCertificateName: setupCertificateName,
}
}
// SetupCertificate ensures that a CA and a certificate is available for the
// webhook server
func (f *WebhookConfig) setupCertificate(ctx context.Context) error {
secretNamespacedName := machinerytypes.NamespacedName{
Name: f.setupCertificateName,
Namespace: f.webhookNamespace,
}
// We have to query for the Secret using an unstructured object because the cache for the structured
// client is not initialized yet at this point in time. See https://github.com/kubernetes-sigs/controller-runtime/issues/180
secret := &unstructured.Unstructured{}
secret.SetGroupVersionKind(schema.GroupVersionKind{
Group: "",
Kind: "Secret",
Version: "v1",
})
err := f.client.Get(ctx, secretNamespacedName, secret)
if err != nil && !k8serrors.IsNotFound(err) {
return err
}
if secret.GetName() != "" {
ctxlog.Info(ctx, "Not creating the webhook server certificate because it already exists")
data := secret.Object["data"].(map[string]interface{})
caKey, err := base64.StdEncoding.DecodeString(data["ca_private_key"].(string))
if err != nil {
return err
}
caCert, err := base64.StdEncoding.DecodeString(data["ca_certificate"].(string))
if err != nil {
return err
}
key, err := base64.StdEncoding.DecodeString(data["private_key"].(string))
if err != nil {
return err
}
cert, err := base64.StdEncoding.DecodeString(data["certificate"].(string))
if err != nil {
return err
}
f.CaKey = caKey
f.CaCertificate = caCert
f.Key = key
f.Certificate = cert
} else {
ctxlog.Info(ctx, "Creating webhook server certificate")
// Generate CA
caRequest := credsgen.CertificateGenerationRequest{
CommonName: "SCF CA",
IsCA: true,
AlternativeNames: []string{f.config.WebhookServerHost},
}
caCert, err := f.generator.GenerateCertificate("webhook-server-ca", caRequest)
if err != nil {
return err
}
commonName := f.config.WebhookServerHost
if len(f.serviceName) > 0 {
if len(f.webhookNamespace) == 0 {
return errors.New("No webhook namespace defined. If you run the extension under a service, you need to specify the service namespace")
}
commonName = fmt.Sprintf("%s.%s.svc", f.serviceName, f.webhookNamespace)
}
// Generate Certificate
request := credsgen.CertificateGenerationRequest{
IsCA: false,
CommonName: commonName,
CA: credsgen.Certificate{
IsCA: true,
PrivateKey: caCert.PrivateKey,
Certificate: caCert.Certificate,
},
}
cert, err := f.generator.GenerateCertificate("webhook-server-cert", request)
if err != nil {
return err
}
newSecret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretNamespacedName.Name,
Namespace: secretNamespacedName.Namespace,
},
Data: map[string][]byte{
"certificate": cert.Certificate,
"private_key": cert.PrivateKey,
"ca_certificate": caCert.Certificate,
"ca_private_key": caCert.PrivateKey,
},
}
err = f.client.Create(ctx, newSecret)
if err != nil {
return err
}
f.CaKey = caCert.PrivateKey
f.CaCertificate = caCert.Certificate
f.Key = cert.PrivateKey
f.Certificate = cert.Certificate
}
err = f.writeSecretFiles()
if err != nil {
return errors.Wrap(err, "writing webhook certificate files to disk")
}
return nil
}
func (f *WebhookConfig) GenerateAdmissionWebhook(webhooks []MutatingWebhook) []admissionregistrationv1beta1.MutatingWebhook {
var mutatingHooks []admissionregistrationv1beta1.MutatingWebhook
for _, webhook := range webhooks {
var clientConfig admissionregistrationv1beta1.WebhookClientConfig
if f.serviceName != "" {
p := webhook.GetPath()
clientConfig = admissionregistrationv1beta1.WebhookClientConfig{
CABundle: f.CaCertificate,
Service: &admissionregistrationv1beta1.ServiceReference{
Name: f.serviceName,
Namespace: f.webhookNamespace,
Path: &p,
Port: &f.config.WebhookServerPort,
},
}
} else {
url := url.URL{
Scheme: "https",
Host: net.JoinHostPort(f.config.WebhookServerHost, strconv.Itoa(int(f.config.WebhookServerPort))),
Path: webhook.GetPath(),
}
urlString := url.String()
clientConfig = admissionregistrationv1beta1.WebhookClientConfig{
CABundle: f.CaCertificate,
URL: &urlString,
}
}
p := webhook.GetFailurePolicy()
wh := admissionregistrationv1beta1.MutatingWebhook{
Name: webhook.GetName(),
Rules: webhook.GetRules(),
FailurePolicy: &p,
NamespaceSelector: webhook.GetNamespaceSelector(),
ClientConfig: clientConfig,
ObjectSelector: webhook.GetLabelSelector(),
}
mutatingHooks = append(mutatingHooks, wh)
}
return mutatingHooks
}
func (f *WebhookConfig) registerWebhooks(ctx context.Context, webhooks []MutatingWebhook) error {
if len(f.CaCertificate) == 0 {
return errors.New("Can not create a webhook server config with an empty ca certificate")
}
config := &admissionregistrationv1beta1.MutatingWebhookConfiguration{
ObjectMeta: metav1.ObjectMeta{
Name: f.ConfigName,
Namespace: f.config.Namespace,
},
Webhooks: f.GenerateAdmissionWebhook(webhooks),
}
f.client.Delete(ctx, config)
err := f.client.Create(ctx, config)
if err != nil {
return errors.Wrap(err, "generating the webhook configuration")
}
return nil
}
func (f *WebhookConfig) writeSecretFiles() error {
if exists, _ := afero.DirExists(f.config.Fs, f.CertDir); !exists {
err := f.config.Fs.Mkdir(f.CertDir, 0700)
if err != nil {
return err
}
}
err := afero.WriteFile(f.config.Fs, path.Join(f.CertDir, "ca-key.pem"), f.CaKey, 0600)
if err != nil {
return err
}
err = afero.WriteFile(f.config.Fs, path.Join(f.CertDir, "ca-cert.pem"), f.CaCertificate, 0644)
if err != nil {
return err
}
err = afero.WriteFile(f.config.Fs, path.Join(f.CertDir, "tls.key"), f.Key, 0600)
if err != nil {
return err
}
err = afero.WriteFile(f.config.Fs, path.Join(f.CertDir, "tls.crt"), f.Certificate, 0644)
if err != nil {
return err
}
return nil
}