File: validation_test.go

package info (click to toggle)
golang-k8s-kube-openapi 0.0~git20241212.2c72e55-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 23,396 kB
  • sloc: sh: 50; makefile: 5
file content (416 lines) | stat: -rw-r--r-- 9,532 bytes parent folder | download
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
/*
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_test

import (
	"fmt"
	"path/filepath"

	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
	"sigs.k8s.io/yaml"

	"k8s.io/kube-openapi/pkg/util/proto"
	"k8s.io/kube-openapi/pkg/util/proto/testing"
	"k8s.io/kube-openapi/pkg/util/proto/validation"
)

var fakeSchema = testing.Fake{Path: filepath.Join("..", "testdata", "swagger.json")}

func Validate(models proto.Models, model string, data string) []error {
	var obj interface{}
	if err := yaml.Unmarshal([]byte(data), &obj); err != nil {
		return []error{fmt.Errorf("pre-validation: failed to parse yaml: %v", err)}
	}
	return ValidateObj(models, model, obj)
}

// ValidateObj validates an object produced by decoding json or yaml.
// Numbers may be int64 or float64.
func ValidateObj(models proto.Models, model string, obj interface{}) []error {
	schema := models.LookupModel(model)
	if schema == nil {
		return []error{fmt.Errorf("pre-validation: couldn't find model %s", model)}
	}

	return validation.ValidateModel(obj, schema, model)
}

var _ = Describe("resource validation using OpenAPI Schema", func() {
	var models proto.Models
	BeforeEach(func() {
		s, err := fakeSchema.OpenAPISchema()
		Expect(err).To(BeNil())
		models, err = proto.NewOpenAPIData(s)
		Expect(err).To(BeNil())
	})

	It("finds Deployment in Schema and validates it", func() {
		err := Validate(models, "io.k8s.api.apps.v1beta1.Deployment", `
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    name: redis-master
  name: name
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
      - image: redis
        name: redis
`)
		Expect(err).To(BeNil())
	})

	It("validates a valid pod", func() {
		err := Validate(models, "io.k8s.api.core.v1.Pod", `
apiVersion: v1
kind: Pod
metadata:
  labels:
    name: redis-master
  name: name
spec:
  containers:
  - args:
    - this
    - is
    - an
    - ok
    - command
    image: gcr.io/fake_project/fake_image:fake_tag
    name: master
`)
		Expect(err).To(BeNil())
	})

	It("finds invalid command (string instead of []string) in Json Pod", func() {
		err := Validate(models, "io.k8s.api.core.v1.Pod", `
{
  "kind": "Pod",
  "apiVersion": "v1",
  "metadata": {
    "name": "name",
    "labels": {
      "name": "redis-master"
    }
  },
  "spec": {
    "containers": [
      {
        "name": "master",
	"image": "gcr.io/fake_project/fake_image:fake_tag",
        "args": "this is a bad command"
      }
    ]
  }
}
`)
		Expect(err).To(Equal([]error{
			validation.ValidationError{
				Path: "io.k8s.api.core.v1.Pod.spec.containers[0].args",
				Err: validation.InvalidTypeError{
					Path:     "io.k8s.api.core.v1.Container.args",
					Expected: "array",
					Actual:   "string",
				},
			},
		}))
	})

	It("fails because hostPort is string instead of int", func() {
		err := Validate(models, "io.k8s.api.core.v1.Pod", `
{
  "kind": "Pod",
  "apiVersion": "v1",
  "metadata": {
    "name": "apache-php",
    "labels": {
      "name": "apache-php"
    }
  },
  "spec": {
    "volumes": [{
        "name": "shared-disk"
    }],
    "containers": [
      {
        "name": "apache-php",
        "image": "gcr.io/fake_project/fake_image:fake_tag",
        "ports": [
          {
            "name": "apache",
            "hostPort": "13380",
            "containerPort": 80,
            "protocol": "TCP"
          }
        ],
        "volumeMounts": [
          {
            "name": "shared-disk",
            "mountPath": "/var/www/html"
          }
        ]
      }
    ]
  }
}
`)

		Expect(err).To(Equal([]error{
			validation.ValidationError{
				Path: "io.k8s.api.core.v1.Pod.spec.containers[0].ports[0].hostPort",
				Err: validation.InvalidTypeError{
					Path:     "io.k8s.api.core.v1.ContainerPort.hostPort",
					Expected: "integer",
					Actual:   "string",
				},
			},
		}))

	})

	It("fails because volume is not an array of object", func() {
		err := Validate(models, "io.k8s.api.core.v1.Pod", `
{
  "kind": "Pod",
  "apiVersion": "v1",
  "metadata": {
    "name": "apache-php",
    "labels": {
      "name": "apache-php"
    }
  },
  "spec": {
    "volumes": [
        "name": "shared-disk"
    ],
    "containers": [
      {
        "name": "apache-php",
	"image": "gcr.io/fake_project/fake_image:fake_tag",
        "ports": [
          {
            "name": "apache",
            "hostPort": 13380,
            "containerPort": 80,
            "protocol": "TCP"
          }
        ],
        "volumeMounts": [
          {
            "name": "shared-disk",
            "mountPath": "/var/www/html"
          }
        ]
      }
    ]
  }
}
`)
		Expect(err).To(BeNil())
	})

	It("fails because some string lists have empty strings", func() {
		err := Validate(models, "io.k8s.api.core.v1.Pod", `
apiVersion: v1
kind: Pod
metadata:
  labels:
    name: redis-master
  name: name
spec:
  containers:
  - image: gcr.io/fake_project/fake_image:fake_tag
    name: master
    args:
    -
    command:
    -
`)

		Expect(err).To(Equal([]error{
			validation.ValidationError{
				Path: "io.k8s.api.core.v1.Pod.spec.containers[0].args",
				Err: validation.InvalidObjectTypeError{
					Path: "io.k8s.api.core.v1.Pod.spec.containers[0].args[0]",
					Type: "nil",
				},
			},
			validation.ValidationError{
				Path: "io.k8s.api.core.v1.Pod.spec.containers[0].command",
				Err: validation.InvalidObjectTypeError{
					Path: "io.k8s.api.core.v1.Pod.spec.containers[0].command[0]",
					Type: "nil",
				},
			},
		}))
	})

	It("fails if required fields are missing", func() {
		err := Validate(models, "io.k8s.api.core.v1.Pod", `
apiVersion: v1
kind: Pod
metadata:
  labels:
    name: redis-master
  name: name
spec:
  containers:
  - command: ["my", "command"]
`)

		Expect(err).To(Equal([]error{
			validation.ValidationError{
				Path: "io.k8s.api.core.v1.Pod.spec.containers[0]",
				Err: validation.MissingRequiredFieldError{
					Path:  "io.k8s.api.core.v1.Container",
					Field: "name",
				},
			},
			validation.ValidationError{
				Path: "io.k8s.api.core.v1.Pod.spec.containers[0]",
				Err: validation.MissingRequiredFieldError{
					Path:  "io.k8s.api.core.v1.Container",
					Field: "image",
				},
			},
		}))
	})

	It("fails if required fields are empty", func() {
		err := Validate(models, "io.k8s.api.core.v1.Pod", `
apiVersion: v1
kind: Pod
metadata:
  labels:
    name: redis-master
  name: name
spec:
  containers:
  - image:
    name:
`)

		Expect(err).To(Equal([]error{
			validation.ValidationError{
				Path: "io.k8s.api.core.v1.Pod.spec.containers[0]",
				Err: validation.MissingRequiredFieldError{
					Path:  "io.k8s.api.core.v1.Container",
					Field: "name",
				},
			},
			validation.ValidationError{
				Path: "io.k8s.api.core.v1.Pod.spec.containers[0]",
				Err: validation.MissingRequiredFieldError{
					Path:  "io.k8s.api.core.v1.Container",
					Field: "image",
				},
			},
		}))
	})

	It("is fine with empty non-mandatory fields", func() {
		err := Validate(models, "io.k8s.api.core.v1.Pod", `
apiVersion: v1
kind: Pod
metadata:
  labels:
    name: redis-master
  name: name
spec:
  containers:
  - image: image
    name: name
    command:
`)

		Expect(err).To(BeNil())
	})

	It("fails because apiVersion is not provided", func() {
		err := Validate(models, "io.k8s.api.core.v1.Pod", `
kind: Pod
metadata:
  name: name
spec:
  containers:
  - name: name
    image: image
`)
		Expect(err).To(BeNil())
	})

	It("fails because apiVersion type is not string and kind is not provided", func() {
		err := Validate(models, "io.k8s.api.core.v1.Pod", `
apiVersion: 1
metadata:
  name: name
spec:
  containers:
  - name: name
    image: image
`)
		Expect(err).To(BeNil())
	})

	// verify integer literals are considered to be compatible with float schema fields
	It("validates integer values for float fields", func() {
		err := ValidateObj(models, "io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinition", map[string]interface{}{
			"apiVersion": "apiextensions.k8s.io/v1",
			"kind":       "CustomResourceDefinition",
			"metadata":   map[string]interface{}{"name": "foo"},
			"spec": map[string]interface{}{
				"scope": "Namespaced",
				"group": "example.com",
				"names": map[string]interface{}{
					"plural": "numbers",
					"kind":   "Number",
				},
				"versions": []interface{}{
					map[string]interface{}{
						"name":    "v1",
						"served":  true,
						"storage": true,
						"schema": map[string]interface{}{
							"openAPIV3Schema": map[string]interface{}{
								"properties": map[string]interface{}{
									"replicas": map[string]interface{}{
										"default": int64(1),
										"minimum": int64(0),
										"type":    "integer",
									},
									"resources": map[string]interface{}{
										"default": float64(1.1),
										"minimum": float64(0.1),
										"type":    "number",
									},
								},
							},
						},
					},
				},
			},
		})
		Expect(err).To(BeNil())
	})
})