forked from kgateway-dev/kgateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5-gateway-validation-webhook-configuration_test.go
412 lines (367 loc) · 14.4 KB
/
5-gateway-validation-webhook-configuration_test.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//go:build ignore
package test
import (
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
"github.com/golang/protobuf/ptypes/wrappers"
"github.com/onsi/gomega/types"
v1 "k8s.io/api/admissionregistration/v1"
glootestutils "github.com/kgateway-dev/kgateway/test/testutils"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/solo-io/go-utils/stringutils"
"github.com/solo-io/k8s-utils/installutils/kuberesource"
. "github.com/solo-io/k8s-utils/manifesttestutils"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/yaml"
gloostringutils "github.com/kgateway-dev/kgateway/pkg/utils/stringutils"
)
const (
validatingWebhookConfigurationKind = "ValidatingWebhookConfiguration"
)
var _ = Describe("WebhookValidationConfiguration helm test", func() {
var allTests = func(rendererTestCase renderTestCase) {
var (
testManifest TestManifest
//expectedChart *unstructured.Unstructured
)
prepareMakefile := func(namespace string, values glootestutils.HelmValues) {
tm, err := rendererTestCase.renderer.RenderManifest(namespace, values)
ExpectWithOffset(1, err).NotTo(HaveOccurred(), "Failed to render manifest")
testManifest = tm
}
DescribeTable("Can remove DELETEs from webhook rules", func(resources []string, expectedRemoved int) {
timeoutSeconds := 5
// Count the "DELETES" as a sanity check.
expectedDeletes := 6 - expectedRemoved
expectedChart := generateExpectedChart(expectedChartArgs{
timeoutSeconds: timeoutSeconds,
skipDeletes: resources,
expectedDeletes: expectedDeletes,
})
prepareMakefile(namespace, glootestutils.HelmValues{
ValuesArgs: []string{
fmt.Sprintf(`gateway.validation.webhook.timeoutSeconds=%d`, timeoutSeconds),
`gateway.validation.webhook.skipDeleteValidationResources={` + strings.Join(resources, ",") + `}`,
},
})
testManifest.ExpectUnstructured(expectedChart.GetKind(), expectedChart.GetNamespace(), expectedChart.GetName()).To(BeEquivalentTo(expectedChart))
},
Entry("virtualservices", []string{"virtualservices"}, 1),
Entry("routetables", []string{"routetables"}, 1),
Entry("gateways", []string{"gateways"}, 0),
Entry("upstreams", []string{"upstreams"}, 1),
Entry("secrets", []string{"secrets"}, 1),
Entry("namespaces", []string{"namespaces"}, 1),
Entry("ratelimitconfigs", []string{"ratelimitconfigs"}, 1),
Entry("mutiple", []string{"virtualservices", "routetables", "secrets"}, 3),
Entry("mutiple (with removal)", []string{"ratelimitconfigs", "secrets"}, 2),
Entry("all", []string{"*"}, 6),
Entry("empty", []string{}, 0),
)
It("Can set gloo failurePolicy", func() {
timeoutSeconds := 5
expectedChart := generateExpectedChart(expectedChartArgs{
timeoutSeconds: timeoutSeconds,
glooFailurePolicy: "Fail",
expectedDeletes: 6,
})
prepareMakefile(namespace, glootestutils.HelmValues{
ValuesArgs: []string{
fmt.Sprintf(`gateway.validation.webhook.timeoutSeconds=%d`, timeoutSeconds),
`gateway.validation.failurePolicy=Fail`,
},
})
testManifest.ExpectUnstructured(expectedChart.GetKind(), expectedChart.GetNamespace(), expectedChart.GetName()).To(BeEquivalentTo(expectedChart))
})
It("Can set kube failurePolicy", func() {
timeoutSeconds := 5
expectedChart := generateExpectedChart(expectedChartArgs{
timeoutSeconds: timeoutSeconds,
kubeFailurePolicy: "Fail",
expectedDeletes: 6,
})
prepareMakefile(namespace, glootestutils.HelmValues{
ValuesArgs: []string{
fmt.Sprintf(`gateway.validation.webhook.timeoutSeconds=%d`, timeoutSeconds),
`gateway.validation.kubeCoreFailurePolicy=Fail`,
},
})
testManifest.ExpectUnstructured(expectedChart.GetKind(), expectedChart.GetNamespace(), expectedChart.GetName()).To(BeEquivalentTo(expectedChart))
})
It("Kube Webhook is not rendered if secrets and resources are skipped", func() {
prepareMakefile(namespace, glootestutils.HelmValues{
ValuesArgs: []string{
`gateway.validation.webhook.skipDeleteValidationResources={secrets,namespaces}`,
},
})
// assert that the kube webhook is not rendered
testManifest.SelectResources(func(resource *unstructured.Unstructured) bool {
return resource.GetKind() == "ValidatingWebhookConfiguration" && resource.GetName() == "gloo-gateway-validation-webhook-"+namespace
}).ExpectAll(func(webhook *unstructured.Unstructured) {
webhookObject, err := kuberesource.ConvertUnstructured(webhook)
ExpectWithOffset(1, err).NotTo(HaveOccurred(), fmt.Sprintf("Webhook %+v should be able to convert from unstructured", webhook))
structuredDeployment, ok := webhookObject.(*admissionregistrationv1.ValidatingWebhookConfiguration)
ExpectWithOffset(1, ok).To(BeTrue(), fmt.Sprintf("Webhook %+v should be able to cast to a structured deployment", webhook))
ExpectWithOffset(1, structuredDeployment.Webhooks).To(HaveLen(1), fmt.Sprintf("Only one webhook should be present on deployment %+v", structuredDeployment))
ExpectWithOffset(1, structuredDeployment.Webhooks[0].Name).To(Equal("gloo."+namespace+".svc"), fmt.Sprintf("Webhook name should be 'gloo.%s.svc' on deployment %+v", namespace, structuredDeployment))
})
})
Context("enablePolicyApi", func() {
// containPolicyApiOperation returns a GomegaMatcher which will assert that a provided ValidatingWebhookConfiguration
// contains the Rule that includes the Policy APIs
containPolicyApiOperation := func() types.GomegaMatcher {
policyApiOperation := v1.RuleWithOperations{
Operations: []v1.OperationType{
v1.Create,
v1.Update,
},
Rule: v1.Rule{
APIGroups: []string{"gateway.solo.io"},
APIVersions: []string{"v1"},
Resources: []string{"routeoptions", "virtualhostoptions"},
},
}
return WithTransform(func(config *v1.ValidatingWebhookConfiguration) []v1.RuleWithOperations {
if config == nil {
return nil
}
return config.Webhooks[0].Rules
}, ContainElement(policyApiOperation))
}
type enablePolicyApiCase struct {
enableKubeGatewayApi *wrappers.BoolValue
enablePolicyApi *wrappers.BoolValue
expectedWebhookConfiguration types.GomegaMatcher
}
DescribeTable("respects helm values",
func(testCase enablePolicyApiCase) {
var valuesArgs []string
if testCase.enableKubeGatewayApi != nil {
valuesArgs = append(valuesArgs, fmt.Sprintf(`kubeGateway.enabled=%t`, testCase.enableKubeGatewayApi.GetValue()))
}
if testCase.enablePolicyApi != nil {
valuesArgs = append(valuesArgs, fmt.Sprintf(`gateway.validation.webhook.enablePolicyApi=%t`, testCase.enablePolicyApi.GetValue()))
}
prepareMakefile(namespace, glootestutils.HelmValues{
ValuesArgs: valuesArgs,
})
testManifest.ExpectUnstructured(
validatingWebhookConfigurationKind,
"", // ValidatingWebhookConfiguration is cluster-scoped
fmt.Sprintf("gloo-gateway-validation-webhook-%s", namespace),
).To(WithTransform(func(unstructuredVwc *unstructured.Unstructured) *v1.ValidatingWebhookConfiguration {
// convert the unstructured validating webhook configuration to a structured object
if unstructuredVwc == nil {
return nil
}
rawJson, err := json.Marshal(unstructuredVwc.Object)
if err != nil {
return nil
}
var structuredVwc *v1.ValidatingWebhookConfiguration
err = json.Unmarshal(rawJson, &structuredVwc)
if err != nil {
return nil
}
return structuredVwc
}, testCase.expectedWebhookConfiguration))
},
Entry("unset", enablePolicyApiCase{
enableKubeGatewayApi: nil,
enablePolicyApi: nil,
expectedWebhookConfiguration: Not(containPolicyApiOperation()),
}),
Entry("enableKubeGatewayApi=false,", enablePolicyApiCase{
enableKubeGatewayApi: &wrappers.BoolValue{Value: false},
enablePolicyApi: nil,
expectedWebhookConfiguration: Not(containPolicyApiOperation()),
}),
Entry("enableKubeGatewayApi=true,", enablePolicyApiCase{
enableKubeGatewayApi: &wrappers.BoolValue{Value: true},
enablePolicyApi: nil, // default is true
expectedWebhookConfiguration: containPolicyApiOperation(),
}),
Entry("enableKubeGatewayApi=true, enablePolicyApi=true", enablePolicyApiCase{
enableKubeGatewayApi: &wrappers.BoolValue{Value: true},
enablePolicyApi: &wrappers.BoolValue{Value: true},
expectedWebhookConfiguration: containPolicyApiOperation(),
}),
// This is the critical test case, which demonstrates that a user can enabled the K8s Gateway Integration,
// but disable validation for the Policy APIs
Entry("enableKubeGatewayApi=false, enablePolicyApi=true", enablePolicyApiCase{
enableKubeGatewayApi: &wrappers.BoolValue{Value: false},
enablePolicyApi: &wrappers.BoolValue{Value: true},
expectedWebhookConfiguration: Not(containPolicyApiOperation()),
}),
Entry("enableKubeGatewayApi=false, enablePolicyApi=true", enablePolicyApiCase{
enableKubeGatewayApi: &wrappers.BoolValue{Value: false},
enablePolicyApi: &wrappers.BoolValue{Value: true},
expectedWebhookConfiguration: Not(containPolicyApiOperation()),
}),
Entry("enableKubeGatewayApi=false, enablePolicyApi=false", enablePolicyApiCase{
enableKubeGatewayApi: &wrappers.BoolValue{Value: false},
enablePolicyApi: &wrappers.BoolValue{Value: false},
expectedWebhookConfiguration: Not(containPolicyApiOperation()),
}),
)
})
}
runTests(allTests)
})
type expectedChartArgs struct {
timeoutSeconds int
skipDeletes []string
expectedDeletes int
glooFailurePolicy string
kubeFailurePolicy string
}
func generateExpectedChart(args expectedChartArgs) *unstructured.Unstructured {
// Default failure policies
if args.glooFailurePolicy == "" {
args.glooFailurePolicy = "Ignore"
}
if args.kubeFailurePolicy == "" {
args.kubeFailurePolicy = "Ignore"
}
GinkgoHelper()
glooRules, coreRules := generateRules(args.skipDeletes)
// indent "rules"
m1 := regexp.MustCompile("\n")
glooRules = m1.ReplaceAllString(glooRules, "\n ")
coreRules = m1.ReplaceAllString(coreRules, "\n ")
// Check that we have the expected number of DELETEs
m2 := regexp.MustCompile(`DELETE`)
deletes := len(m2.FindAllStringIndex(glooRules, -1)) + len(m2.FindAllStringIndex(coreRules, -1))
Expect(deletes).To(Equal(args.expectedDeletes))
chart := `
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: gloo-gateway-validation-webhook-` + namespace + `
labels:
app: gloo
gloo: gateway
annotations:
"helm.sh/hook": pre-install, pre-upgrade
"helm.sh/hook-weight": "5" # should come before cert-gen job
webhooks:
- name: gloo.` + namespace + `.svc # must be a domain with at least three segments separated by dots
clientConfig:
service:
name: gloo
namespace: ` + namespace + `
path: "/validation"
caBundle: "" # update manually or use certgen job
rules:
` + glooRules + `
sideEffects: None
matchPolicy: Exact
timeoutSeconds: ` + strconv.Itoa(args.timeoutSeconds) + `
admissionReviewVersions:
- v1beta1
failurePolicy: ` + args.glooFailurePolicy + `
`
// Only create the webhook for core resources if there are any resources being valdiated
if coreRules != "[]\n " {
chart += `- name: kube.` + namespace + `.svc # must be a domain with at least three segments separated by dots
clientConfig:
service:
name: gloo
namespace: ` + namespace + `
path: "/validation"
caBundle: "" # update manually or use certgen job
rules:
` + coreRules + `
sideEffects: None
matchPolicy: Exact
timeoutSeconds: ` + strconv.Itoa(args.timeoutSeconds) + `
admissionReviewVersions:
- v1beta1
failurePolicy: ` + args.kubeFailurePolicy + `
`
}
return makeUnstructured(chart)
}
// generateRules returns gloo rules and core rules as separate strings
func generateRules(skipDeleteReources []string) (string, string) {
GinkgoHelper()
glooRules := []map[string][]string{
{
"operations": {"CREATE", "UPDATE", "DELETE"},
"apiGroups": {"gateway.solo.io"},
"apiVersions": {"v1"},
"resources": {"virtualservices"},
},
{
"operations": {"CREATE", "UPDATE", "DELETE"},
"apiGroups": {"gateway.solo.io"},
"apiVersions": {"v1"},
"resources": {"routetables"},
},
{
"operations": {"CREATE", "UPDATE"},
"apiGroups": {"gateway.solo.io"},
"apiVersions": {"v1"},
"resources": {"gateways"},
},
{
"operations": {"CREATE", "UPDATE", "DELETE"},
"apiGroups": {"gloo.solo.io"},
"apiVersions": {"v1"},
"resources": {"upstreams"},
},
{
"operations": {"CREATE", "UPDATE", "DELETE"},
"apiGroups": {"ratelimit.solo.io"},
"apiVersions": {"v1alpha1"},
"resources": {"ratelimitconfigs"},
},
}
coreRules := []map[string][]string{
{
"operations": {"DELETE"},
"apiGroups": {""},
"apiVersions": {"v1"},
"resources": {"secrets"},
},
{
"operations": {"UPDATE", "DELETE"},
"apiGroups": {""},
"apiVersions": {"v1"},
"resources": {"namespaces"},
},
}
finalGlooRules := []map[string][]string{}
for i, rule := range glooRules {
if stringutils.ContainsAny([]string{rule["resources"][0], "*"}, skipDeleteReources) {
rule["operations"] = gloostringutils.DeleteOneByValue(rule["operations"], "DELETE")
}
if len(rule["operations"]) != 0 {
finalGlooRules = append(finalGlooRules, glooRules[i])
}
}
finalNonGlooRules := []map[string][]string{}
for i, rule := range coreRules {
if stringutils.ContainsAny([]string{rule["resources"][0], "*"}, skipDeleteReources) {
rule["operations"] = gloostringutils.DeleteOneByValue(rule["operations"], "DELETE")
// A namespace with an update to a label can cause it to no longer be watched,
// equivalent to deleting it from the controller's perspective
if rule["resources"][0] == "namespaces" {
rule["operations"] = gloostringutils.DeleteOneByValue(rule["operations"], "UPDATE")
}
}
if len(rule["operations"]) != 0 {
finalNonGlooRules = append(finalNonGlooRules, coreRules[i])
}
}
glooRulesYaml, err := yaml.Marshal(finalGlooRules)
Expect(err).NotTo(HaveOccurred())
nonGlooRulesYaml, err := yaml.Marshal(finalNonGlooRules)
Expect(err).NotTo(HaveOccurred())
return string(glooRulesYaml), string(nonGlooRulesYaml)
}