-
Notifications
You must be signed in to change notification settings - Fork 2k
/
apiserver.go
307 lines (268 loc) · 9.26 KB
/
apiserver.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/*
Copyright 2020 The cert-manager 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 framework
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
apiextensionsinstall "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/install"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
jsonserializer "k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/apimachinery/pkg/runtime/serializer/versioning"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/rest"
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/envtest"
webhooktesting "github.com/jetstack/cert-manager/cmd/webhook/app/testing"
"github.com/jetstack/cert-manager/internal/test/paths"
"github.com/jetstack/cert-manager/internal/webhook"
"github.com/jetstack/cert-manager/pkg/api"
"github.com/jetstack/cert-manager/pkg/webhook/handlers"
"github.com/jetstack/cert-manager/test/internal/apiserver"
)
type StopFunc func()
// controlPlaneOptions has parameters for the control plane of the integration
// test framework which can be overridden in tests.
type controlPlaneOptions struct {
crdsDir *string
webhookConversionHandler handlers.ConversionHook
}
type RunControlPlaneOption func(*controlPlaneOptions)
// WithCRDDirectory allows alternative CRDs to be loaded into the test API
// server in tests.
func WithCRDDirectory(directory string) RunControlPlaneOption {
return func(o *controlPlaneOptions) {
o.crdsDir = pointer.StringPtr(directory)
}
}
// WithWebhookConversionHandler allows the webhook handler for the `/convert`
// endpoint to be overridden in tests.
func WithWebhookConversionHandler(handler handlers.ConversionHook) RunControlPlaneOption {
return func(o *controlPlaneOptions) {
o.webhookConversionHandler = handler
}
}
func RunControlPlane(t *testing.T, ctx context.Context, optionFunctions ...RunControlPlaneOption) (*rest.Config, StopFunc) {
options := &controlPlaneOptions{
crdsDir: pointer.StringPtr(paths.CRDDirectory(t)),
}
for _, f := range optionFunctions {
f(options)
}
env, stopControlPlane := apiserver.RunBareControlPlane(t)
testuser, err := env.ControlPlane.AddUser(envtest.User{Name: "test-user", Groups: []string{"cluster-admin"}}, env.Config)
if err != nil {
t.Fatal(err)
}
kubeconfig, err := testuser.KubeConfig()
if err != nil {
t.Fatal(err)
}
f, err := ioutil.TempFile("", "integration-")
if err != nil {
t.Fatal(err)
}
defer f.Close()
defer func() {
os.Remove(f.Name())
}()
if _, err := f.Write(kubeconfig); err != nil {
t.Fatal(err)
}
webhookOpts, stopWebhook := webhooktesting.StartWebhookServer(
t, ctx, []string{"--kubeconfig", f.Name()},
webhook.WithConversionHandler(options.webhookConversionHandler),
)
crds := readCustomResourcesAtPath(t, *options.crdsDir)
for _, crd := range crds {
t.Logf("Found CRD with name %q", crd.Name)
}
patchCRDConversion(crds, webhookOpts.URL, webhookOpts.CAPEM)
if _, err := envtest.InstallCRDs(env.Config, envtest.CRDInstallOptions{
CRDs: crds,
}); err != nil {
t.Fatal(err)
}
cl, err := client.New(env.Config, client.Options{Scheme: api.Scheme})
if err != nil {
t.Fatal(err)
}
// installing the validating webhooks, not using WebhookInstallOptions as it patches the CA to be it's own
err = cl.Create(ctx, getValidatingWebhookConfig(webhookOpts.URL, webhookOpts.CAPEM))
if err != nil {
t.Fatal(err)
}
// installing the mutating webhooks, not using WebhookInstallOptions as it patches the CA to be it's own
err = cl.Create(ctx, getMutatingWebhookConfig(webhookOpts.URL, webhookOpts.CAPEM))
if err != nil {
t.Fatal(err)
}
return env.Config, func() {
defer stopWebhook()
stopControlPlane()
}
}
var (
internalScheme = runtime.NewScheme()
)
func init() {
utilruntime.Must(metav1.AddMetaToScheme(internalScheme))
apiextensionsinstall.Install(internalScheme)
}
// patchCRDConversion overrides the conversion configuration of the CRDs that
// are loaded in to the integration test API server,
// configuring the conversion to be handled by the local webhook server.
func patchCRDConversion(crds []*apiextensionsv1.CustomResourceDefinition, url string, caPEM []byte) {
for i := range crds {
url := fmt.Sprintf("%s%s", url, "/convert")
crds[i].Spec.Conversion = &apiextensionsv1.CustomResourceConversion{
Strategy: apiextensionsv1.WebhookConverter,
Webhook: &apiextensionsv1.WebhookConversion{
ClientConfig: &apiextensionsv1.WebhookClientConfig{
URL: &url,
CABundle: caPEM,
},
ConversionReviewVersions: []string{"v1"},
},
}
}
}
func readCustomResourcesAtPath(t *testing.T, path string) []*apiextensionsv1.CustomResourceDefinition {
serializer := jsonserializer.NewSerializerWithOptions(jsonserializer.DefaultMetaFactory, internalScheme, internalScheme, jsonserializer.SerializerOptions{
Yaml: true,
})
converter := runtime.UnsafeObjectConvertor(internalScheme)
codec := versioning.NewCodec(serializer, serializer, converter, internalScheme, internalScheme, internalScheme, runtime.InternalGroupVersioner, runtime.InternalGroupVersioner, internalScheme.Name())
var crds []*apiextensionsv1.CustomResourceDefinition
if err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if filepath.Ext(path) != ".yaml" {
return nil
}
crd, err := readCRDsAtPath(codec, converter, path)
if err != nil {
return fmt.Errorf("failed reading CRDs at path %s: %w", path, err)
}
crds = append(crds, crd...)
return nil
}); err != nil {
t.Fatal(err)
}
return crds
}
func readCRDsAtPath(codec runtime.Codec, converter runtime.ObjectConvertor, path string) ([]*apiextensionsv1.CustomResourceDefinition, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var crds []*apiextensionsv1.CustomResourceDefinition
for _, d := range strings.Split(string(data), "\n---\n") {
// skip empty YAML documents
if strings.TrimSpace(d) == "" {
continue
}
internalCRD := &apiextensions.CustomResourceDefinition{}
if _, _, err := codec.Decode([]byte(d), nil, internalCRD); err != nil {
return nil, err
}
out := apiextensionsv1.CustomResourceDefinition{}
if err := converter.Convert(internalCRD, &out, nil); err != nil {
return nil, err
}
crds = append(crds, &out)
}
return crds, nil
}
func getValidatingWebhookConfig(url string, caPEM []byte) client.Object {
failurePolicy := admissionregistrationv1.Fail
sideEffects := admissionregistrationv1.SideEffectClassNone
validateURL := fmt.Sprintf("%s/validate", url)
webhook := admissionregistrationv1.ValidatingWebhookConfiguration{
ObjectMeta: metav1.ObjectMeta{
Name: "cert-manager-webhook",
},
Webhooks: []admissionregistrationv1.ValidatingWebhook{
{
Name: "webhook.cert-manager.io",
ClientConfig: admissionregistrationv1.WebhookClientConfig{
URL: &validateURL,
CABundle: caPEM,
},
Rules: []admissionregistrationv1.RuleWithOperations{
{
Operations: []admissionregistrationv1.OperationType{
admissionregistrationv1.Create,
admissionregistrationv1.Update,
},
Rule: admissionregistrationv1.Rule{
APIGroups: []string{"cert-manager.io", "acme.cert-manager.io"},
APIVersions: []string{"*"},
Resources: []string{"*/*"},
},
},
},
FailurePolicy: &failurePolicy,
SideEffects: &sideEffects,
AdmissionReviewVersions: []string{"v1"},
},
},
}
return &webhook
}
func getMutatingWebhookConfig(url string, caPEM []byte) client.Object {
failurePolicy := admissionregistrationv1.Fail
sideEffects := admissionregistrationv1.SideEffectClassNone
validateURL := fmt.Sprintf("%s/mutate", url)
webhook := admissionregistrationv1.MutatingWebhookConfiguration{
ObjectMeta: metav1.ObjectMeta{
Name: "cert-manager-webhook",
},
Webhooks: []admissionregistrationv1.MutatingWebhook{
{
Name: "webhook.cert-manager.io",
ClientConfig: admissionregistrationv1.WebhookClientConfig{
URL: &validateURL,
CABundle: caPEM,
},
Rules: []admissionregistrationv1.RuleWithOperations{
{
Operations: []admissionregistrationv1.OperationType{
admissionregistrationv1.Create,
admissionregistrationv1.Update,
},
Rule: admissionregistrationv1.Rule{
APIGroups: []string{"cert-manager.io", "acme.cert-manager.io"},
APIVersions: []string{"*"},
Resources: []string{"*/*"},
},
},
},
FailurePolicy: &failurePolicy,
SideEffects: &sideEffects,
AdmissionReviewVersions: []string{"v1"},
},
},
}
return &webhook
}