forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 5
/
validation_test.go
507 lines (485 loc) · 18.9 KB
/
validation_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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
/*
Copyright 2017 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 validation
import (
"math/rand"
"os"
"strconv"
"testing"
"time"
"github.com/google/go-cmp/cmp"
kjson "sigs.k8s.io/json"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
apiextensionsfuzzer "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/fuzzer"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/api/apitesting/fuzzer"
apiequality "k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/util/json"
"k8s.io/apimachinery/pkg/util/sets"
kubeopenapispec "k8s.io/kube-openapi/pkg/validation/spec"
)
// TestRoundTrip checks the conversion to go-openapi types.
// internal -> go-openapi -> JSON -> external -> internal
func TestRoundTrip(t *testing.T) {
scheme := runtime.NewScheme()
codecs := serializer.NewCodecFactory(scheme)
// add internal and external types to scheme
if err := apiextensions.AddToScheme(scheme); err != nil {
t.Fatal(err)
}
if err := apiextensionsv1.AddToScheme(scheme); err != nil {
t.Fatal(err)
}
seed := int64(time.Now().Nanosecond())
if override := os.Getenv("TEST_RAND_SEED"); len(override) > 0 {
overrideSeed, err := strconv.Atoi(override)
if err != nil {
t.Fatal(err)
}
seed = int64(overrideSeed)
t.Logf("using overridden seed: %d", seed)
} else {
t.Logf("seed (override with TEST_RAND_SEED if desired): %d", seed)
}
fuzzerFuncs := fuzzer.MergeFuzzerFuncs(apiextensionsfuzzer.Funcs)
f := fuzzer.FuzzerFor(fuzzerFuncs, rand.NewSource(seed), codecs)
for i := 0; i < 50; i++ {
// fuzz internal types
internal := &apiextensions.JSONSchemaProps{}
f.Fuzz(internal)
// internal -> go-openapi
openAPITypes := &kubeopenapispec.Schema{}
if err := ConvertJSONSchemaProps(internal, openAPITypes); err != nil {
t.Fatal(err)
}
// go-openapi -> JSON
openAPIJSON, err := json.Marshal(openAPITypes)
if err != nil {
t.Fatal(err)
}
// JSON -> in-memory JSON => convertNullTypeToNullable => JSON
var j interface{}
if strictErrs, err := kjson.UnmarshalStrict(openAPIJSON, &j); err != nil {
t.Fatal(err)
} else if len(strictErrs) > 0 {
t.Fatal(strictErrs)
}
j = stripIntOrStringType(j)
openAPIJSON, err = json.Marshal(j)
if err != nil {
t.Fatal(err)
}
// JSON -> external
external := &apiextensionsv1.JSONSchemaProps{}
if strictErrs, err := kjson.UnmarshalStrict(openAPIJSON, external); err != nil {
t.Fatal(err)
} else if len(strictErrs) > 0 {
t.Fatal(strictErrs)
}
// external -> internal
internalRoundTripped := &apiextensions.JSONSchemaProps{}
if err := scheme.Convert(external, internalRoundTripped, nil); err != nil {
t.Fatal(err)
}
if !apiequality.Semantic.DeepEqual(internal, internalRoundTripped) {
t.Log(string(openAPIJSON))
t.Fatalf("%d: unexpected diff\n\t%s", i, cmp.Diff(internal, internalRoundTripped))
}
}
}
func stripIntOrStringType(x interface{}) interface{} {
switch x := x.(type) {
case map[string]interface{}:
if t, found := x["type"]; found {
switch t := t.(type) {
case []interface{}:
if len(t) == 2 && t[0] == "integer" && t[1] == "string" && x["x-kubernetes-int-or-string"] == true {
delete(x, "type")
}
}
}
for k := range x {
x[k] = stripIntOrStringType(x[k])
}
return x
case []interface{}:
for i := range x {
x[i] = stripIntOrStringType(x[i])
}
return x
default:
return x
}
}
type failingObject struct {
object interface{}
expectErrs []string
}
func TestValidateCustomResource(t *testing.T) {
tests := []struct {
name string
schema apiextensions.JSONSchemaProps
objects []interface{}
failingObjects []failingObject
}{
{name: "!nullable",
schema: apiextensions.JSONSchemaProps{
Properties: map[string]apiextensions.JSONSchemaProps{
"field": {
Type: "object",
Nullable: false,
},
},
},
objects: []interface{}{
map[string]interface{}{},
map[string]interface{}{"field": map[string]interface{}{}},
},
failingObjects: []failingObject{
{object: map[string]interface{}{"field": "foo"}, expectErrs: []string{`field: Invalid value: "string": field in body must be of type object: "string"`}},
{object: map[string]interface{}{"field": 42}, expectErrs: []string{`field: Invalid value: "integer": field in body must be of type object: "integer"`}},
{object: map[string]interface{}{"field": true}, expectErrs: []string{`field: Invalid value: "boolean": field in body must be of type object: "boolean"`}},
{object: map[string]interface{}{"field": 1.2}, expectErrs: []string{`field: Invalid value: "number": field in body must be of type object: "number"`}},
{object: map[string]interface{}{"field": []interface{}{}}, expectErrs: []string{`field: Invalid value: "array": field in body must be of type object: "array"`}},
{object: map[string]interface{}{"field": nil}, expectErrs: []string{`field: Invalid value: "null": field in body must be of type object: "null"`}},
},
},
{name: "nullable",
schema: apiextensions.JSONSchemaProps{
Properties: map[string]apiextensions.JSONSchemaProps{
"field": {
Type: "object",
Nullable: true,
},
},
},
objects: []interface{}{
map[string]interface{}{},
map[string]interface{}{"field": map[string]interface{}{}},
map[string]interface{}{"field": nil},
},
failingObjects: []failingObject{
{object: map[string]interface{}{"field": "foo"}, expectErrs: []string{`field: Invalid value: "string": field in body must be of type object: "string"`}},
{object: map[string]interface{}{"field": 42}, expectErrs: []string{`field: Invalid value: "integer": field in body must be of type object: "integer"`}},
{object: map[string]interface{}{"field": true}, expectErrs: []string{`field: Invalid value: "boolean": field in body must be of type object: "boolean"`}},
{object: map[string]interface{}{"field": 1.2}, expectErrs: []string{`field: Invalid value: "number": field in body must be of type object: "number"`}},
{object: map[string]interface{}{"field": []interface{}{}}, expectErrs: []string{`field: Invalid value: "array": field in body must be of type object: "array"`}},
},
},
{name: "nullable and no type",
schema: apiextensions.JSONSchemaProps{
Properties: map[string]apiextensions.JSONSchemaProps{
"field": {
Nullable: true,
},
},
},
objects: []interface{}{
map[string]interface{}{},
map[string]interface{}{"field": map[string]interface{}{}},
map[string]interface{}{"field": nil},
map[string]interface{}{"field": "foo"},
map[string]interface{}{"field": 42},
map[string]interface{}{"field": true},
map[string]interface{}{"field": 1.2},
map[string]interface{}{"field": []interface{}{}},
},
},
{name: "x-kubernetes-int-or-string",
schema: apiextensions.JSONSchemaProps{
Properties: map[string]apiextensions.JSONSchemaProps{
"field": {
XIntOrString: true,
},
},
},
objects: []interface{}{
map[string]interface{}{},
map[string]interface{}{"field": 42},
map[string]interface{}{"field": "foo"},
},
failingObjects: []failingObject{
{object: map[string]interface{}{"field": nil}, expectErrs: []string{`field: Invalid value: "null": field in body must be of type integer,string: "null"`}},
{object: map[string]interface{}{"field": true}, expectErrs: []string{`field: Invalid value: "boolean": field in body must be of type integer,string: "boolean"`}},
{object: map[string]interface{}{"field": 1.2}, expectErrs: []string{`field: Invalid value: "number": field in body must be of type integer,string: "number"`}},
{object: map[string]interface{}{"field": map[string]interface{}{}}, expectErrs: []string{`field: Invalid value: "object": field in body must be of type integer,string: "object"`}},
{object: map[string]interface{}{"field": []interface{}{}}, expectErrs: []string{`field: Invalid value: "array": field in body must be of type integer,string: "array"`}},
},
},
{name: "nullable and x-kubernetes-int-or-string",
schema: apiextensions.JSONSchemaProps{
Properties: map[string]apiextensions.JSONSchemaProps{
"field": {
Nullable: true,
XIntOrString: true,
},
},
},
objects: []interface{}{
map[string]interface{}{},
map[string]interface{}{"field": 42},
map[string]interface{}{"field": "foo"},
map[string]interface{}{"field": nil},
},
failingObjects: []failingObject{
{object: map[string]interface{}{"field": true}, expectErrs: []string{`field: Invalid value: "boolean": field in body must be of type integer,string: "boolean"`}},
{object: map[string]interface{}{"field": 1.2}, expectErrs: []string{`field: Invalid value: "number": field in body must be of type integer,string: "number"`}},
{object: map[string]interface{}{"field": map[string]interface{}{}}, expectErrs: []string{`field: Invalid value: "object": field in body must be of type integer,string: "object"`}},
{object: map[string]interface{}{"field": []interface{}{}}, expectErrs: []string{`field: Invalid value: "array": field in body must be of type integer,string: "array"`}},
},
},
{name: "nullable, x-kubernetes-int-or-string and user-provided anyOf",
schema: apiextensions.JSONSchemaProps{
Properties: map[string]apiextensions.JSONSchemaProps{
"field": {
Nullable: true,
XIntOrString: true,
AnyOf: []apiextensions.JSONSchemaProps{
{Type: "integer"},
{Type: "string"},
},
},
},
},
objects: []interface{}{
map[string]interface{}{},
map[string]interface{}{"field": nil},
map[string]interface{}{"field": 42},
map[string]interface{}{"field": "foo"},
},
failingObjects: []failingObject{
{object: map[string]interface{}{"field": true}, expectErrs: []string{
`<nil>: Invalid value: "": "field" must validate at least one schema (anyOf)`,
`field: Invalid value: "boolean": field in body must be of type integer,string: "boolean"`,
`field: Invalid value: "boolean": field in body must be of type integer: "boolean"`,
}},
{object: map[string]interface{}{"field": 1.2}, expectErrs: []string{
`<nil>: Invalid value: "": "field" must validate at least one schema (anyOf)`,
`field: Invalid value: "number": field in body must be of type integer,string: "number"`,
`field: Invalid value: "number": field in body must be of type integer: "number"`,
}},
{object: map[string]interface{}{"field": map[string]interface{}{}}, expectErrs: []string{
`<nil>: Invalid value: "": "field" must validate at least one schema (anyOf)`,
`field: Invalid value: "object": field in body must be of type integer,string: "object"`,
`field: Invalid value: "object": field in body must be of type integer: "object"`,
}},
{object: map[string]interface{}{"field": []interface{}{}}, expectErrs: []string{
`<nil>: Invalid value: "": "field" must validate at least one schema (anyOf)`,
`field: Invalid value: "array": field in body must be of type integer,string: "array"`,
`field: Invalid value: "array": field in body must be of type integer: "array"`,
}},
},
},
{name: "nullable, x-kubernetes-int-or-string and user-provider allOf",
schema: apiextensions.JSONSchemaProps{
Properties: map[string]apiextensions.JSONSchemaProps{
"field": {
Nullable: true,
XIntOrString: true,
AllOf: []apiextensions.JSONSchemaProps{
{
AnyOf: []apiextensions.JSONSchemaProps{
{Type: "integer"},
{Type: "string"},
},
},
},
},
},
},
objects: []interface{}{
map[string]interface{}{},
map[string]interface{}{"field": nil},
map[string]interface{}{"field": 42},
map[string]interface{}{"field": "foo"},
},
failingObjects: []failingObject{
{object: map[string]interface{}{"field": true}, expectErrs: []string{
`<nil>: Invalid value: "": "field" must validate all the schemas (allOf). None validated`,
`<nil>: Invalid value: "": "field" must validate at least one schema (anyOf)`,
`field: Invalid value: "boolean": field in body must be of type integer,string: "boolean"`,
`field: Invalid value: "boolean": field in body must be of type integer: "boolean"`,
}},
{object: map[string]interface{}{"field": 1.2}, expectErrs: []string{
`<nil>: Invalid value: "": "field" must validate all the schemas (allOf). None validated`,
`<nil>: Invalid value: "": "field" must validate at least one schema (anyOf)`,
`field: Invalid value: "number": field in body must be of type integer,string: "number"`,
`field: Invalid value: "number": field in body must be of type integer: "number"`,
}},
{object: map[string]interface{}{"field": map[string]interface{}{}}, expectErrs: []string{
`<nil>: Invalid value: "": "field" must validate all the schemas (allOf). None validated`,
`<nil>: Invalid value: "": "field" must validate at least one schema (anyOf)`,
`field: Invalid value: "object": field in body must be of type integer,string: "object"`,
`field: Invalid value: "object": field in body must be of type integer: "object"`,
}},
{object: map[string]interface{}{"field": []interface{}{}}, expectErrs: []string{
`<nil>: Invalid value: "": "field" must validate all the schemas (allOf). None validated`,
`<nil>: Invalid value: "": "field" must validate at least one schema (anyOf)`,
`field: Invalid value: "array": field in body must be of type integer,string: "array"`,
`field: Invalid value: "array": field in body must be of type integer: "array"`,
}},
},
},
{name: "invalid regex",
schema: apiextensions.JSONSchemaProps{
Properties: map[string]apiextensions.JSONSchemaProps{
"field": {
Type: "string",
Pattern: "+",
},
},
},
failingObjects: []failingObject{
{object: map[string]interface{}{"field": "foo"}, expectErrs: []string{"field: Invalid value: \"foo\": field in body should match '+, but pattern is invalid: error parsing regexp: missing argument to repetition operator: `+`'"}},
},
},
{name: "required field",
schema: apiextensions.JSONSchemaProps{
Required: []string{"field"},
Properties: map[string]apiextensions.JSONSchemaProps{
"field": {
Type: "object",
Required: []string{"nested"},
Properties: map[string]apiextensions.JSONSchemaProps{
"nested": {},
},
},
},
},
failingObjects: []failingObject{
{object: map[string]interface{}{"test": "a"}, expectErrs: []string{`field: Required value`}},
{object: map[string]interface{}{"field": map[string]interface{}{}}, expectErrs: []string{`field.nested: Required value`}},
},
},
{name: "enum",
schema: apiextensions.JSONSchemaProps{
Properties: map[string]apiextensions.JSONSchemaProps{
"field": {
Type: "object",
Required: []string{"nestedint", "nestedstring"},
Properties: map[string]apiextensions.JSONSchemaProps{
"nestedint": {
Type: "integer",
Enum: []apiextensions.JSON{1, 2},
},
"nestedstring": {
Type: "string",
Enum: []apiextensions.JSON{"a", "b"},
},
},
},
},
},
failingObjects: []failingObject{
{object: map[string]interface{}{"field": map[string]interface{}{}}, expectErrs: []string{
`field.nestedint: Required value`,
`field.nestedstring: Required value`,
}},
{object: map[string]interface{}{"field": map[string]interface{}{"nestedint": "x", "nestedstring": true}}, expectErrs: []string{
`field.nestedint: Invalid value: "string": field.nestedint in body must be of type integer: "string"`,
`field.nestedint: Unsupported value: "x": supported values: "1", "2"`,
`field.nestedstring: Invalid value: "boolean": field.nestedstring in body must be of type string: "boolean"`,
`field.nestedstring: Unsupported value: true: supported values: "a", "b"`,
}},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
validator, _, err := NewSchemaValidator(&apiextensions.CustomResourceValidation{OpenAPIV3Schema: &tt.schema})
if err != nil {
t.Fatal(err)
}
for _, obj := range tt.objects {
if errs := ValidateCustomResource(nil, obj, validator); len(errs) > 0 {
t.Errorf("unexpected validation error for %v: %v", obj, errs)
}
}
for i, failingObject := range tt.failingObjects {
if errs := ValidateCustomResource(nil, failingObject.object, validator); len(errs) == 0 {
t.Errorf("missing error for %v", failingObject.object)
} else {
sawErrors := sets.NewString()
for _, err := range errs {
sawErrors.Insert(err.Error())
}
expectErrs := sets.NewString(failingObject.expectErrs...)
for _, unexpectedError := range sawErrors.Difference(expectErrs).List() {
t.Errorf("%d: unexpected error: %s", i, unexpectedError)
}
for _, missingError := range expectErrs.Difference(sawErrors).List() {
t.Errorf("%d: missing error: %s", i, missingError)
}
}
}
})
}
}
func TestItemsProperty(t *testing.T) {
type args struct {
schema apiextensions.JSONSchemaProps
object interface{}
}
tests := []struct {
name string
args args
wantErr bool
}{
{"items in object", args{
apiextensions.JSONSchemaProps{
Properties: map[string]apiextensions.JSONSchemaProps{
"spec": {
Properties: map[string]apiextensions.JSONSchemaProps{
"replicas": {
Type: "integer",
},
},
},
},
},
map[string]interface{}{"spec": map[string]interface{}{"replicas": 1, "items": []string{"1", "2"}}},
}, false},
{"items in array", args{
apiextensions.JSONSchemaProps{
Properties: map[string]apiextensions.JSONSchemaProps{
"secrets": {
Type: "array",
Items: &apiextensions.JSONSchemaPropsOrArray{
Schema: &apiextensions.JSONSchemaProps{
Type: "string",
},
},
},
},
},
map[string]interface{}{"secrets": []string{"1", "2"}},
}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
validator, _, err := NewSchemaValidator(&apiextensions.CustomResourceValidation{OpenAPIV3Schema: &tt.args.schema})
if err != nil {
t.Fatal(err)
}
if errs := ValidateCustomResource(nil, tt.args.object, validator); (len(errs) > 0) != tt.wantErr {
if len(errs) == 0 {
t.Error("expected error, but didn't get one")
} else {
t.Errorf("unexpected validation error: %v", errs)
}
}
})
}
}