-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
openapi.go
303 lines (275 loc) · 8.52 KB
/
openapi.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
package openapi
import (
"encoding/json"
"fmt"
"strings"
"github.com/emicklei/go-restful"
restfulspec "github.com/emicklei/go-restful-openapi"
"github.com/go-openapi/errors"
"github.com/go-openapi/spec"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/validate"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/kube-openapi/pkg/builder"
"k8s.io/kube-openapi/pkg/common"
"kubevirt.io/client-go/api"
)
type Validator struct {
specSchemes *spec.Schema
statusSchemes *spec.Schema
topLevelKeys map[string]interface{}
}
func CreateOpenAPIConfig(webServices []*restful.WebService) restfulspec.Config {
return restfulspec.Config{
WebServices: webServices,
WebServicesURL: "",
APIPath: "/swaggerapi",
PostBuildSwaggerObjectHandler: addInfoToSwaggerObject,
}
}
func addInfoToSwaggerObject(swo *spec.Swagger) {
swo.Info = &spec.Info{
InfoProps: spec.InfoProps{
Title: "KubeVirt API",
Description: "This is KubeVirt API an add-on for Kubernetes.",
Contact: &spec.ContactInfo{
ContactInfoProps: spec.ContactInfoProps{
Name: "kubevirt-dev",
Email: "kubevirt-dev@googlegroups.com",
URL: "https://github.com/kubevirt/kubevirt",
},
},
License: &spec.License{
LicenseProps: spec.LicenseProps{
Name: "Apache 2.0",
URL: "https://www.apache.org/licenses/LICENSE-2.0",
},
},
},
}
swo.SecurityDefinitions = spec.SecurityDefinitions{
"BearerToken": &spec.SecurityScheme{
SecuritySchemeProps: spec.SecuritySchemeProps{
Type: "apiKey",
Name: "authorization",
In: "header",
Description: "Bearer Token authentication",
},
},
}
swo.Swagger = "2.0"
swo.Security = make([]map[string][]string, 1)
swo.Security[0] = map[string][]string{"BearerToken": {}}
}
func createConfig() *common.Config {
return &common.Config{
CommonResponses: map[int]spec.Response{
401: {
ResponseProps: spec.ResponseProps{
Description: "Unauthorized",
},
},
},
Info: &spec.Info{
InfoProps: spec.InfoProps{
Title: "KubeVirt API",
Description: "This is KubeVirt API an add-on for Kubernetes.",
Contact: &spec.ContactInfo{
ContactInfoProps: spec.ContactInfoProps{
Name: "kubevirt-dev",
Email: "kubevirt-dev@googlegroups.com",
URL: "https://github.com/kubevirt/kubevirt",
},
},
License: &spec.License{
LicenseProps: spec.LicenseProps{
Name: "Apache 2.0",
URL: "https://www.apache.org/licenses/LICENSE-2.0",
},
},
},
},
SecurityDefinitions: &spec.SecurityDefinitions{
"BearerToken": &spec.SecurityScheme{
SecuritySchemeProps: spec.SecuritySchemeProps{
Type: "apiKey",
Name: "authorization",
In: "header",
Description: "Bearer Token authentication",
},
},
},
GetDefinitions: func(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition {
m := api.GetOpenAPIDefinitions(ref)
for k, v := range m {
if _, ok := m[k]; !ok {
m[k] = v
}
}
return m
},
GetDefinitionName: func(name string) (string, spec.Extensions) {
if strings.Contains(name, "kubevirt.io") {
// keeping for validation
return name[strings.LastIndex(name, "/")+1:], nil
}
//adpting k8s style
return strings.ReplaceAll(name, "/", "."), nil
},
}
}
func LoadOpenAPISpec(webServices []*restful.WebService) *spec.Swagger {
config := createConfig()
openapispec, err := builder.BuildOpenAPISpec(webServices, config)
if err != nil {
panic(fmt.Errorf("Failed to build swagger: %s", err))
}
// creationTimestamp, lastProbeTime and lastTransitionTime are deserialized as "null"
// Fix it here until
// https://github.com/kubernetes/kubernetes/issues/66899 is ready
// Otherwise CRDs can't use templates which contain metadata and controllers
// can't set conditions without timestamps
objectmeta := ""
for k := range openapispec.Definitions {
if strings.Contains(k, "v1.ObjectMeta") {
objectmeta = k
break
}
}
resourceRequirements, exists := openapispec.Definitions["v1.ResourceRequirements"]
if exists {
limits, exists := resourceRequirements.Properties["limits"]
if exists {
limits.AdditionalProperties = nil
resourceRequirements.Properties["limits"] = limits
}
requests, exists := resourceRequirements.Properties["requests"]
if exists {
requests.AdditionalProperties = nil
resourceRequirements.Properties["requests"] = requests
}
}
objectMeta, exists := openapispec.Definitions[objectmeta]
if exists {
prop := objectMeta.Properties["creationTimestamp"]
prop.Type = spec.StringOrArray{"string", "null"}
// mask v1.Time as in validation v1.Time override sting,null type
prop.Ref = spec.Ref{}
objectMeta.Properties["creationTimestamp"] = prop
}
for k, s := range openapispec.Definitions {
// allow nullable statuses
if status, found := s.Properties["status"]; found {
if !status.Type.Contains("string") {
definitionName := strings.Split(status.Ref.GetPointer().String(), "/")[2]
object := openapispec.Definitions[definitionName]
object.Nullable = true
openapispec.Definitions[definitionName] = object
}
}
if strings.HasSuffix(k, "Condition") {
prop := s.Properties["lastProbeTime"]
prop.Type = spec.StringOrArray{"string", "null"}
prop.Ref = spec.Ref{}
s.Properties["lastProbeTime"] = prop
prop = s.Properties["lastTransitionTime"]
prop.Type = spec.StringOrArray{"string", "null"}
prop.Ref = spec.Ref{}
s.Properties["lastTransitionTime"] = prop
}
if strings.Contains(k, "v1.HTTPGetAction") {
prop := s.Properties["port"]
prop.Type = spec.StringOrArray{"string", "number"}
// As intstr.IntOrString, the ref for that must be masked
prop.Ref = spec.Ref{}
s.Properties["port"] = prop
}
if strings.Contains(k, "v1.TCPSocketAction") {
prop := s.Properties["port"]
prop.Type = spec.StringOrArray{"string", "number"}
// As intstr.IntOrString, the ref for that must be masked
prop.Ref = spec.Ref{}
s.Properties["port"] = prop
}
if strings.Contains(k, "v1.PersistentVolumeClaimSpec") {
for i, r := range s.Required {
if r == "dataSource" {
s.Required = append(s.Required[:i], s.Required[i+1:]...)
openapispec.Definitions[k] = s
break
}
}
}
}
return openapispec
}
func CreateOpenAPIValidator(webServices []*restful.WebService) *Validator {
openapispec := LoadOpenAPISpec(webServices)
data, err := json.Marshal(openapispec)
if err != nil {
glog.Fatal(err)
}
specSchema := &spec.Schema{}
err = json.Unmarshal(data, specSchema)
if err != nil {
panic(err)
}
// Make sure that no unknown fields are allowed in specs
for k, v := range specSchema.Definitions {
v.AdditionalProperties = &spec.SchemaOrBool{Allows: false}
v.AdditionalItems = &spec.SchemaOrBool{Allows: false}
specSchema.Definitions[k] = v
}
// Expand the specSchemes
err = spec.ExpandSchema(specSchema, specSchema, nil)
if err != nil {
glog.Fatal(err)
}
// Load spec once again for status. The status should accept unknown fields
statusSchema := &spec.Schema{}
err = json.Unmarshal(data, statusSchema)
if err != nil {
panic(err)
}
// Expand the statusSchemes
err = spec.ExpandSchema(statusSchema, statusSchema, nil)
if err != nil {
glog.Fatal(err)
}
return &Validator{
specSchemes: specSchema,
statusSchemes: statusSchema,
topLevelKeys: map[string]interface{}{
"kind": nil,
"apiVersion": nil,
"spec": nil,
"status": nil,
"metadata": nil,
},
}
}
func (v *Validator) Validate(gvk schema.GroupVersionKind, obj map[string]interface{}) []error {
errs := []error{}
for k := range obj {
if _, exists := v.topLevelKeys[k]; !exists {
errs = append(errs, errors.PropertyNotAllowed("", "body", k))
}
}
if value, exists := obj["spec"]; !exists {
errs = append(errs, errors.Required("spec", "body", value))
}
errs = append(errs, v.ValidateSpec(gvk, obj)...)
errs = append(errs, v.ValidateStatus(gvk, obj)...)
return errs
}
func (v *Validator) ValidateSpec(gvk schema.GroupVersionKind, obj map[string]interface{}) []error {
schema := v.specSchemes.Definitions["v1."+gvk.Kind+"Spec"]
result := validate.NewSchemaValidator(&schema, nil, "spec", strfmt.Default).Validate(obj["spec"])
return result.Errors
}
func (v *Validator) ValidateStatus(gvk schema.GroupVersionKind, obj map[string]interface{}) []error {
schema := v.statusSchemes.Definitions["v1."+gvk.Kind+"Status"]
result := validate.NewSchemaValidator(&schema, nil, "status", strfmt.Default).Validate(obj["status"])
return result.Errors
}