Debian Codegraph @

pkg/validation/spec/schema.go

raw
1 // Copyright 2015 go-swagger maintainers
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package spec
16
17 import (
18 "encoding/json"
19 "fmt"
20 "net/url"
21 "strings"
22
23 "github.com/go-openapi/swag"
24 "k8s.io/kube-openapi/pkg/internal"
25 jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json"
26 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext"
27 )
28
29 // BooleanProperty creates a boolean property
30 func BooleanProperty() *Schema {
31 return &Schema{SchemaProps: SchemaProps{Type: []string{"boolean"}}}
32 }
33
34 // BoolProperty creates a boolean property
35 func BoolProperty() *Schema { return BooleanProperty() }
36
37 // StringProperty creates a string property
38 func StringProperty() *Schema {
39 return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}
40 }
41
42 // CharProperty creates a string property
43 func CharProperty() *Schema {
44 return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}
45 }
46
47 // Float64Property creates a float64/double property
48 func Float64Property() *Schema {
49 return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "double"}}
50 }
51
52 // Float32Property creates a float32/float property
53 func Float32Property() *Schema {
54 return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "float"}}
55 }
56
57 // Int8Property creates an int8 property
58 func Int8Property() *Schema {
59 return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int8"}}
60 }
61
62 // Int16Property creates an int16 property
63 func Int16Property() *Schema {
64 return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int16"}}
65 }
66
67 // Int32Property creates an int32 property
68 func Int32Property() *Schema {
69 return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int32"}}
70 }
71
72 // Int64Property creates an int64 property
73 func Int64Property() *Schema {
74 return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int64"}}
75 }
76
77 // StrFmtProperty creates a property for the named string format
78 func StrFmtProperty(format string) *Schema {
79 return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: format}}
80 }
81
82 // DateProperty creates a date property
83 func DateProperty() *Schema {
84 return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date"}}
85 }
86
87 // DateTimeProperty creates a date time property
88 func DateTimeProperty() *Schema {
89 return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date-time"}}
90 }
91
92 // MapProperty creates a map property
93 func MapProperty(property *Schema) *Schema {
94 return &Schema{SchemaProps: SchemaProps{Type: []string{"object"},
95 AdditionalProperties: &SchemaOrBool{Allows: true, Schema: property}}}
96 }
97
98 // RefProperty creates a ref property
99 func RefProperty(name string) *Schema {
100 return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}}
101 }
102
103 // RefSchema creates a ref property
104 func RefSchema(name string) *Schema {
105 return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}}
106 }
107
108 // ArrayProperty creates an array property
109 func ArrayProperty(items *Schema) *Schema {
110 if items == nil {
111 return &Schema{SchemaProps: SchemaProps{Type: []string{"array"}}}
112 }
113 return &Schema{SchemaProps: SchemaProps{Items: &SchemaOrArray{Schema: items}, Type: []string{"array"}}}
114 }
115
116 // ComposedSchema creates a schema with allOf
117 func ComposedSchema(schemas ...Schema) *Schema {
118 s := new(Schema)
119 s.AllOf = schemas
120 return s
121 }
122
123 // SchemaURL represents a schema url
124 type SchemaURL string
125
126 // MarshalJSON marshal this to JSON
127 func (r SchemaURL) MarshalJSON() ([]byte, error) {
128 if r == "" {
129 return []byte("{}"), nil
130 }
131 v := map[string]interface{}{"$schema": string(r)}
132 return json.Marshal(v)
133 }
134
135 // UnmarshalJSON unmarshal this from JSON
136 func (r *SchemaURL) UnmarshalJSON(data []byte) error {
137 var v map[string]interface{}
138 if err := json.Unmarshal(data, &v); err != nil {
139 return err
140 }
141 return r.fromMap(v)
142 }
143
144 func (r *SchemaURL) fromMap(v map[string]interface{}) error {
145 if v == nil {
146 return nil
147 }
148 if vv, ok := v["$schema"]; ok {
149 if str, ok := vv.(string); ok {
150 u, err := url.Parse(str)
151 if err != nil {
152 return err
153 }
154
155 *r = SchemaURL(u.String())
156 }
157 }
158 return nil
159 }
160
161 // SchemaProps describes a JSON schema (draft 4)
162 type SchemaProps struct {
163 ID string `json:"id,omitempty"`
164 Ref Ref `json:"-"`
165 Schema SchemaURL `json:"-"`
166 Description string `json:"description,omitempty"`
167 Type StringOrArray `json:"type,omitempty"`
168 Nullable bool `json:"nullable,omitempty"`
169 Format string `json:"format,omitempty"`
170 Title string `json:"title,omitempty"`
171 Default interface{} `json:"default,omitempty"`
172 Maximum *float64 `json:"maximum,omitempty"`
173 ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"`
174 Minimum *float64 `json:"minimum,omitempty"`
175 ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"`
176 MaxLength *int64 `json:"maxLength,omitempty"`
177 MinLength *int64 `json:"minLength,omitempty"`
178 Pattern string `json:"pattern,omitempty"`
179 MaxItems *int64 `json:"maxItems,omitempty"`
180 MinItems *int64 `json:"minItems,omitempty"`
181 UniqueItems bool `json:"uniqueItems,omitempty"`
182 MultipleOf *float64 `json:"multipleOf,omitempty"`
183 Enum []interface{} `json:"enum,omitempty"`
184 MaxProperties *int64 `json:"maxProperties,omitempty"`
185 MinProperties *int64 `json:"minProperties,omitempty"`
186 Required []string `json:"required,omitempty"`
187 Items *SchemaOrArray `json:"items,omitempty"`
188 AllOf []Schema `json:"allOf,omitempty"`
189 OneOf []Schema `json:"oneOf,omitempty"`
190 AnyOf []Schema `json:"anyOf,omitempty"`
191 Not *Schema `json:"not,omitempty"`
192 Properties map[string]Schema `json:"properties,omitempty"`
193 AdditionalProperties *SchemaOrBool `json:"additionalProperties,omitempty"`
194 PatternProperties map[string]Schema `json:"patternProperties,omitempty"`
195 Dependencies Dependencies `json:"dependencies,omitempty"`
196 AdditionalItems *SchemaOrBool `json:"additionalItems,omitempty"`
197 Definitions Definitions `json:"definitions,omitempty"`
198 }
199
200 // Marshaling structure only, always edit along with corresponding
201 // struct (or compilation will fail).
202 type schemaPropsOmitZero struct {
203 ID string `json:"id,omitempty"`
204 Ref Ref `json:"-"`
205 Schema SchemaURL `json:"-"`
206 Description string `json:"description,omitempty"`
207 Type StringOrArray `json:"type,omitzero"`
208 Nullable bool `json:"nullable,omitzero"`
209 Format string `json:"format,omitempty"`
210 Title string `json:"title,omitempty"`
211 Default interface{} `json:"default,omitzero"`
212 Maximum *float64 `json:"maximum,omitempty"`
213 ExclusiveMaximum bool `json:"exclusiveMaximum,omitzero"`
214 Minimum *float64 `json:"minimum,omitempty"`
215 ExclusiveMinimum bool `json:"exclusiveMinimum,omitzero"`
216 MaxLength *int64 `json:"maxLength,omitempty"`
217 MinLength *int64 `json:"minLength,omitempty"`
218 Pattern string `json:"pattern,omitempty"`
219 MaxItems *int64 `json:"maxItems,omitempty"`
220 MinItems *int64 `json:"minItems,omitempty"`
221 UniqueItems bool `json:"uniqueItems,omitzero"`
222 MultipleOf *float64 `json:"multipleOf,omitempty"`
223 Enum []interface{} `json:"enum,omitempty"`
224 MaxProperties *int64 `json:"maxProperties,omitempty"`
225 MinProperties *int64 `json:"minProperties,omitempty"`
226 Required []string `json:"required,omitempty"`
227 Items *SchemaOrArray `json:"items,omitzero"`
228 AllOf []Schema `json:"allOf,omitempty"`
229 OneOf []Schema `json:"oneOf,omitempty"`
230 AnyOf []Schema `json:"anyOf,omitempty"`
231 Not *Schema `json:"not,omitzero"`
232 Properties map[string]Schema `json:"properties,omitempty"`
233 AdditionalProperties *SchemaOrBool `json:"additionalProperties,omitzero"`
234 PatternProperties map[string]Schema `json:"patternProperties,omitempty"`
235 Dependencies Dependencies `json:"dependencies,omitempty"`
236 AdditionalItems *SchemaOrBool `json:"additionalItems,omitzero"`
237 Definitions Definitions `json:"definitions,omitempty"`
238 }
239
240 // SwaggerSchemaProps are additional properties supported by swagger schemas, but not JSON-schema (draft 4)
241 type SwaggerSchemaProps struct {
242 Discriminator string `json:"discriminator,omitempty"`
243 ReadOnly bool `json:"readOnly,omitempty"`
244 ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
245 Example interface{} `json:"example,omitempty"`
246 }
247
248 // Marshaling structure only, always edit along with corresponding
249 // struct (or compilation will fail).
250 type swaggerSchemaPropsOmitZero struct {
251 Discriminator string `json:"discriminator,omitempty"`
252 ReadOnly bool `json:"readOnly,omitzero"`
253 ExternalDocs *ExternalDocumentation `json:"externalDocs,omitzero"`
254 Example interface{} `json:"example,omitempty"`
255 }
256
257 // Schema the schema object allows the definition of input and output data types.
258 // These types can be objects, but also primitives and arrays.
259 // This object is based on the [JSON Schema Specification Draft 4](http://json-schema.org/)
260 // and uses a predefined subset of it.
261 // On top of this subset, there are extensions provided by this specification to allow for more complete documentation.
262 //
263 // For more information: http://goo.gl/8us55a#schemaObject
264 type Schema struct {
265 VendorExtensible
266 SchemaProps
267 SwaggerSchemaProps
268 ExtraProps map[string]interface{} `json:"-"`
269 }
270
271 // WithID sets the id for this schema, allows for chaining
272 func (s *Schema) WithID(id string) *Schema {
273 s.ID = id
274 return s
275 }
276
277 // WithTitle sets the title for this schema, allows for chaining
278 func (s *Schema) WithTitle(title string) *Schema {
279 s.Title = title
280 return s
281 }
282
283 // WithDescription sets the description for this schema, allows for chaining
284 func (s *Schema) WithDescription(description string) *Schema {
285 s.Description = description
286 return s
287 }
288
289 // WithProperties sets the properties for this schema
290 func (s *Schema) WithProperties(schemas map[string]Schema) *Schema {
291 s.Properties = schemas
292 return s
293 }
294
295 // SetProperty sets a property on this schema
296 func (s *Schema) SetProperty(name string, schema Schema) *Schema {
297 if s.Properties == nil {
298 s.Properties = make(map[string]Schema)
299 }
300 s.Properties[name] = schema
301 return s
302 }
303
304 // WithAllOf sets the all of property
305 func (s *Schema) WithAllOf(schemas ...Schema) *Schema {
306 s.AllOf = schemas
307 return s
308 }
309
310 // WithMaxProperties sets the max number of properties an object can have
311 func (s *Schema) WithMaxProperties(max int64) *Schema {
312 s.MaxProperties = &max
313 return s
314 }
315
316 // WithMinProperties sets the min number of properties an object must have
317 func (s *Schema) WithMinProperties(min int64) *Schema {
318 s.MinProperties = &min
319 return s
320 }
321
322 // Typed sets the type of this schema for a single value item
323 func (s *Schema) Typed(tpe, format string) *Schema {
324 s.Type = []string{tpe}
325 s.Format = format
326 return s
327 }
328
329 // AddType adds a type with potential format to the types for this schema
330 func (s *Schema) AddType(tpe, format string) *Schema {
331 s.Type = append(s.Type, tpe)
332 if format != "" {
333 s.Format = format
334 }
335 return s
336 }
337
338 // AsNullable flags this schema as nullable.
339 func (s *Schema) AsNullable() *Schema {
340 s.Nullable = true
341 return s
342 }
343
344 // CollectionOf a fluent builder method for an array parameter
345 func (s *Schema) CollectionOf(items Schema) *Schema {
346 s.Type = []string{jsonArray}
347 s.Items = &SchemaOrArray{Schema: &items}
348 return s
349 }
350
351 // WithDefault sets the default value on this parameter
352 func (s *Schema) WithDefault(defaultValue interface{}) *Schema {
353 s.Default = defaultValue
354 return s
355 }
356
357 // WithRequired flags this parameter as required
358 func (s *Schema) WithRequired(items ...string) *Schema {
359 s.Required = items
360 return s
361 }
362
363 // AddRequired adds field names to the required properties array
364 func (s *Schema) AddRequired(items ...string) *Schema {
365 s.Required = append(s.Required, items...)
366 return s
367 }
368
369 // WithMaxLength sets a max length value
370 func (s *Schema) WithMaxLength(max int64) *Schema {
371 s.MaxLength = &max
372 return s
373 }
374
375 // WithMinLength sets a min length value
376 func (s *Schema) WithMinLength(min int64) *Schema {
377 s.MinLength = &min
378 return s
379 }
380
381 // WithPattern sets a pattern value
382 func (s *Schema) WithPattern(pattern string) *Schema {
383 s.Pattern = pattern
384 return s
385 }
386
387 // WithMultipleOf sets a multiple of value
388 func (s *Schema) WithMultipleOf(number float64) *Schema {
389 s.MultipleOf = &number
390 return s
391 }
392
393 // WithMaximum sets a maximum number value
394 func (s *Schema) WithMaximum(max float64, exclusive bool) *Schema {
395 s.Maximum = &max
396 s.ExclusiveMaximum = exclusive
397 return s
398 }
399
400 // WithMinimum sets a minimum number value
401 func (s *Schema) WithMinimum(min float64, exclusive bool) *Schema {
402 s.Minimum = &min
403 s.ExclusiveMinimum = exclusive
404 return s
405 }
406
407 // WithEnum sets a the enum values (replace)
408 func (s *Schema) WithEnum(values ...interface{}) *Schema {
409 s.Enum = append([]interface{}{}, values...)
410 return s
411 }
412
413 // WithMaxItems sets the max items
414 func (s *Schema) WithMaxItems(size int64) *Schema {
415 s.MaxItems = &size
416 return s
417 }
418
419 // WithMinItems sets the min items
420 func (s *Schema) WithMinItems(size int64) *Schema {
421 s.MinItems = &size
422 return s
423 }
424
425 // UniqueValues dictates that this array can only have unique items
426 func (s *Schema) UniqueValues() *Schema {
427 s.UniqueItems = true
428 return s
429 }
430
431 // AllowDuplicates this array can have duplicates
432 func (s *Schema) AllowDuplicates() *Schema {
433 s.UniqueItems = false
434 return s
435 }
436
437 // AddToAllOf adds a schema to the allOf property
438 func (s *Schema) AddToAllOf(schemas ...Schema) *Schema {
439 s.AllOf = append(s.AllOf, schemas...)
440 return s
441 }
442
443 // WithDiscriminator sets the name of the discriminator field
444 func (s *Schema) WithDiscriminator(discriminator string) *Schema {
445 s.Discriminator = discriminator
446 return s
447 }
448
449 // AsReadOnly flags this schema as readonly
450 func (s *Schema) AsReadOnly() *Schema {
451 s.ReadOnly = true
452 return s
453 }
454
455 // AsWritable flags this schema as writeable (not read-only)
456 func (s *Schema) AsWritable() *Schema {
457 s.ReadOnly = false
458 return s
459 }
460
461 // WithExample sets the example for this schema
462 func (s *Schema) WithExample(example interface{}) *Schema {
463 s.Example = example
464 return s
465 }
466
467 // WithExternalDocs sets/removes the external docs for/from this schema.
468 // When you pass empty strings as params the external documents will be removed.
469 // When you pass non-empty string as one value then those values will be used on the external docs object.
470 // So when you pass a non-empty description, you should also pass the url and vice versa.
471 func (s *Schema) WithExternalDocs(description, url string) *Schema {
472 if description == "" && url == "" {
473 s.ExternalDocs = nil
474 return s
475 }
476
477 if s.ExternalDocs == nil {
478 s.ExternalDocs = &ExternalDocumentation{}
479 }
480 s.ExternalDocs.Description = description
481 s.ExternalDocs.URL = url
482 return s
483 }
484
485 // MarshalJSON marshal this to JSON
486 func (s Schema) MarshalJSON() ([]byte, error) {
487 if internal.UseOptimizedJSONMarshaling {
488 return internal.DeterministicMarshal(s)
489 }
490 b1, err := json.Marshal(s.SchemaProps)
491 if err != nil {
492 return nil, fmt.Errorf("schema props %v", err)
493 }
494 b2, err := json.Marshal(s.VendorExtensible)
495 if err != nil {
496 return nil, fmt.Errorf("vendor props %v", err)
497 }
498 b3, err := s.Ref.MarshalJSON()
499 if err != nil {
500 return nil, fmt.Errorf("ref prop %v", err)
501 }
502 b4, err := s.Schema.MarshalJSON()
503 if err != nil {
504 return nil, fmt.Errorf("schema prop %v", err)
505 }
506 b5, err := json.Marshal(s.SwaggerSchemaProps)
507 if err != nil {
508 return nil, fmt.Errorf("common validations %v", err)
509 }
510 var b6 []byte
511 if s.ExtraProps != nil {
512 jj, err := json.Marshal(s.ExtraProps)
513 if err != nil {
514 return nil, fmt.Errorf("extra props %v", err)
515 }
516 b6 = jj
517 }
518 return swag.ConcatJSON(b1, b2, b3, b4, b5, b6), nil
519 }
520
521 func (s Schema) MarshalJSONTo(enc *jsontext.Encoder) error {
522 type ArbitraryKeys map[string]interface{}
523 var x struct {
524 ArbitraryKeys ArbitraryKeys `json:",inline"`
525 SchemaProps schemaPropsOmitZero `json:",inline"`
526 SwaggerSchemaProps swaggerSchemaPropsOmitZero `json:",inline"`
527 Schema string `json:"$schema,omitempty"`
528 Ref string `json:"$ref,omitempty"`
529 }
530 x.ArbitraryKeys = make(map[string]any, len(s.Extensions)+len(s.ExtraProps))
531 for k, v := range s.Extensions {
532 if internal.IsExtensionKey(k) {
533 x.ArbitraryKeys[k] = v
534 }
535 }
536 for k, v := range s.ExtraProps {
537 x.ArbitraryKeys[k] = v
538 }
539 x.SchemaProps = schemaPropsOmitZero(s.SchemaProps)
540 x.SwaggerSchemaProps = swaggerSchemaPropsOmitZero(s.SwaggerSchemaProps)
541 x.Ref = s.Ref.String()
542 x.Schema = string(s.Schema)
543 return jsonv2.MarshalEncode(enc, x)
544 }
545
546 // UnmarshalJSON marshal this from JSON
547 func (s *Schema) UnmarshalJSON(data []byte) error {
548 if internal.UseOptimizedJSONUnmarshaling {
549 return jsonv2.Unmarshal(data, s)
550 }
551
552 props := struct {
553 SchemaProps
554 SwaggerSchemaProps
555 }{}
556 if err := json.Unmarshal(data, &props); err != nil {
557 return err
558 }
559
560 sch := Schema{
561 SchemaProps: props.SchemaProps,
562 SwaggerSchemaProps: props.SwaggerSchemaProps,
563 }
564
565 var d map[string]interface{}
566 if err := json.Unmarshal(data, &d); err != nil {
567 return err
568 }
569
570 _ = sch.Ref.fromMap(d)
571 _ = sch.Schema.fromMap(d)
572
573 delete(d, "$ref")
574 delete(d, "$schema")
575 for _, pn := range swag.DefaultJSONNameProvider.GetJSONNames(s) {
576 delete(d, pn)
577 }
578
579 for k, vv := range d {
580 lk := strings.ToLower(k)
581 if strings.HasPrefix(lk, "x-") {
582 if sch.Extensions == nil {
583 sch.Extensions = map[string]interface{}{}
584 }
585 sch.Extensions[k] = vv
586 continue
587 }
588 if sch.ExtraProps == nil {
589 sch.ExtraProps = map[string]interface{}{}
590 }
591 sch.ExtraProps[k] = vv
592 }
593
594 *s = sch
595
596 return nil
597 }
598
599 func (s *Schema) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
600 var x struct {
601 Extensions Extensions `json:",inline"`
602 SchemaProps
603 SwaggerSchemaProps
604 }
605 if err := jsonv2.UnmarshalDecode(dec, &x); err != nil {
606 return err
607 }
608
609 if err := x.Ref.fromMap(x.Extensions); err != nil {
610 return err
611 }
612
613 if err := x.Schema.fromMap(x.Extensions); err != nil {
614 return err
615 }
616
617 delete(x.Extensions, "$ref")
618 delete(x.Extensions, "$schema")
619
620 for _, pn := range swag.DefaultJSONNameProvider.GetJSONNames(s) {
621 delete(x.Extensions, pn)
622 }
623 if len(x.Extensions) == 0 {
624 x.Extensions = nil
625 }
626
627 s.ExtraProps = x.Extensions.sanitizeWithExtra()
628 s.Extensions = internal.SanitizeExtensions(x.Extensions)
629 s.SchemaProps = x.SchemaProps
630 s.SwaggerSchemaProps = x.SwaggerSchemaProps
631 return nil
632 }