Repository navigation
Expand file tree
/
Copy pathvalidator.go
More file actions
1473 lines (1302 loc) · 43.1 KB
/
Copy pathvalidator.go
File metadata and controls
1473 lines (1302 loc) · 43.1 KB
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package walle
import (
"encoding/json"
"fmt"
"sort"
"strconv"
"strings"
)
type KeywordValidatorFunc func(any, *validationContext, schemaPath) error
type schemaValidator struct {
context *validationContext
keywordValidators map[string]KeywordValidatorFunc
validateLengthRange KeywordValidatorFunc
validateNumericRange KeywordValidatorFunc
validateItemsRange KeywordValidatorFunc
defDepths map[string]int
totalPropKeys int
terminationMemo map[string]bool
refWalkSteps int
utils *validateUtils
config SchemaValidatorConfig
}
// maxRefWalkSteps caps the total number of nodes the reference walkers (defs
// depth computation and reference termination checking) may visit during one
// validation. Chains of definitions forming diamonds -- or diamonds closing a
// long cycle -- cost 2^n walks without memoization; past this budget
// validation fails closed instead of hanging on adversarial schemas. Honest
// schemas stay orders of magnitude below it: memoized walks are linear in the
// number of definitions.
const maxRefWalkSteps = 500000
func newSchemaValidator(options ...SchemaValidatorOption) *schemaValidator {
config := DefaultValidatorConfig()
for _, option := range options {
option(&config)
}
kv := newKeywordValidators(&config)
validator := &schemaValidator{
context: newValidationContext(),
keywordValidators: make(map[string]KeywordValidatorFunc),
defDepths: make(map[string]int),
totalPropKeys: 0,
utils: &validateUtils{},
config: config,
}
// Register keyword validators
validator.keywordValidators[Type] = kv.ValidateType
validator.keywordValidators[Properties] = kv.ValidateProperties
validator.keywordValidators[Required] = kv.ValidateRequired
validator.keywordValidators[Enum] = kv.ValidateEnum
validator.keywordValidators[Items] = kv.ValidateItems
validator.keywordValidators[Ref] = kv.ValidateRef
validator.keywordValidators[Description] = kv.ValidateDescription
validator.keywordValidators[Title] = kv.ValidateTitle
validator.keywordValidators[AnyOf] = kv.ValidateAnyOf
validator.keywordValidators[AdditionalProperties] = kv.ValidateAdditionalProperties
validator.keywordValidators[Defs] = kv.ValidateDefs
validator.keywordValidators[Id] = kv.ValidateID
validator.keywordValidators[Pattern] = kv.ValidatePattern
validator.keywordValidators[Default] = kv.ValidateDefault
validator.validateLengthRange = kv.ValidateLengthRange
validator.validateNumericRange = kv.ValidateNumericRange
validator.validateItemsRange = kv.ValidateItemsRange
return validator
}
// Reset resets the validator state
func (v *schemaValidator) Reset() {
v.context = newValidationContext()
v.defDepths = make(map[string]int)
v.totalPropKeys = 0
v.terminationMemo = nil
v.refWalkSteps = 0
// won't reset config
}
func (v *schemaValidator) MakePath(base schemaPath, parts ...string) schemaPath {
if base.IsRoot() {
return newSchemaPathFromParts(parts)
}
return base.Append(parts...)
}
func (v *schemaValidator) CheckAnyOfConflicts(schema SchemaDict, path schemaPath) error {
anyOf, ok := schema[AnyOf]
if !ok {
return nil
}
// Get outer keywords (excluding anyOf itself)
outerKeywords := make(map[string]struct{})
for k := range schema {
if k != AnyOf {
outerKeywords[k] = struct{}{}
}
}
// Check each anyOf branch
anyOfSchemas, ok := anyOf.(SchemaList)
if !ok {
return v.context.RaiseErrorWithSimplify("anyOf must be an array", path.Append(AnyOf), SimplifyRemoveAnyOf)
}
for _, subschema := range anyOfSchemas {
schemaObj, ok := subschema.(SchemaDict)
if !ok {
return v.context.RaiseErrorWithSimplify("schema in anyOf must be an object", path.Append(AnyOf), SimplifyRemoveAnyOf)
}
// Check branch keywords against outer keywords
branchKeywords := make(map[string]struct{})
for k := range schemaObj {
branchKeywords[k] = struct{}{}
}
var conflicts []string
for k := range branchKeywords {
if _, exists := outerKeywords[k]; exists {
// Constraining an instance both directly and inside a branch is legal
// under 2020-12: both apply and the effective constraint is their
// conjunction. Only the canonicalising levels report it, so that
// Canonical distributes the parent copy into the branches while looser
// levels accept the schema as written.
if !(v.config.IsUltra() || v.config.IsTest()) {
continue
}
conflicts = append(conflicts, k)
}
}
if len(conflicts) > 0 {
sort.Strings(conflicts)
return v.context.RaiseErrorWithSimplify(
fmt.Sprintf(
`conflicting keywords found in anyOf with parent: keywords (%s) are defined on the parent schema and inside anyOf; remove them from the parent or from anyOf branches`,
strings.Join(conflicts, ", "),
),
path, simplifyFuncForAnyOfParentConflicts(conflicts),
)
}
}
return nil
}
// TraverseSchema traverses and validates a schema
func (v *schemaValidator) TraverseSchema(schema SchemaDict, path schemaPath, currentDepth int) (int, error) {
maxDepth := currentDepth
if currentDepth > v.config.MaxSchemaDepth {
return currentDepth, v.context.RaiseError(fmt.Sprintf("schema depth exceeds maximum limit of %d", v.config.MaxSchemaDepth), path)
}
if schema == nil {
return currentDepth, nil
}
// Verify if it contains unsupported keywords
var unsupported []string
for k := range schema {
if _, ok := SupportedKeywords[k]; !ok && !FutureKeywords[k] {
unsupported = append(unsupported, k)
}
}
if len(unsupported) > 0 && (v.config.IsUltra() || v.config.IsTest()) {
sort.Strings(unsupported)
// Drop just the unsupported keywords; the enforcer ignores keys it does not
// know, so keeping the rest of the schema is both safe and closer to intent.
return currentDepth, v.context.RaiseErrorWithSimplify(
fmt.Sprintf("unsupported keywords: %s", strings.Join(unsupported, ", ")),
path, SimplifyRemoveSchemaKeys(unsupported),
)
}
// Process $defs first
if defs, ok := schema[Defs].(SchemaDict); ok {
keywords := make([]string, 0, len(defs))
for keyword := range defs {
keywords = append(keywords, keyword)
}
sort.Strings(keywords)
for _, keyword := range keywords {
value := defs[keyword]
defSchemaObj, ok := value.(SchemaDict)
if !ok {
return currentDepth, v.context.RaiseErrorWithSimplify("$defs schema must be object", path.Append(Defs), SimplifyRemoveDefs)
}
depth, err := v.TraverseSchema(
defSchemaObj,
v.MakePath(path, Defs, keyword),
currentDepth,
)
if err != nil {
return currentDepth, err
}
if depth > maxDepth {
maxDepth = depth
}
}
}
// A contradiction between $ref and its siblings is reported before any other
// $ref rule. The rules below delete siblings to canonicalise the node, and
// once a contradicting sibling is gone the remaining schema happily accepts
// what the original rejected.
//
// Strict and above reject it, matching how a lower bound above its upper bound
// is handled: both are contradictions inside one node, and neither used to
// stop lite. Looser levels accept the schema and rely on canonicalisation to
// drop the contradicting keyword.
if _, hasRef := schema[Ref]; hasRef && v.config.IsGreaterThanStrict() {
if keyword := v.refSiblingContradiction(schema, path); keyword != "" {
return currentDepth, v.context.RaiseErrorWithSimplify(
fmt.Sprintf(
"%s conflicts with the referenced schema: the intersection is empty, so no instance can satisfy both",
keyword,
),
path, SimplifyDropContradictingRefSibling,
)
}
}
// Check type and anyOf/ref conflicts
if _, hasType := schema[Type]; hasType {
if _, hasAnyOf := schema[AnyOf]; hasAnyOf {
// A type beside anyOf is legal under 2020-12: it applies on top of
// whichever branch matches. The enforcer's anyOf cannot carry a conjunct,
// so only the canonicalising levels report it and the type is pushed into
// the branches; looser levels accept the schema as written.
if v.config.IsUltra() || v.config.IsTest() {
return currentDepth, v.context.RaiseErrorWithSimplify(
"when using anyOf, type should be defined in anyOf items instead of the parent schema",
path, SimplifyDistributeAnyOfParent,
)
}
}
if _, hasRef := schema[Ref]; hasRef {
// A compatible type next to $ref is legal under 2020-12: both assertions
// apply and the intersection is non-empty, which the check above already
// established. Only the canonicalising levels fold it away, so looser
// levels accept the schema as written.
if v.config.IsUltra() || v.config.IsTest() {
return currentDepth, v.context.RaiseErrorWithSimplify(
"when using $ref, type should be defined in the referenced schema instead of the parent schema",
path, SimplifyRemoveType,
)
}
}
if typeList, ok := schema[Type].(SchemaList); ok && len(typeList) > 1 {
if _, hasEnum := schema[Enum]; hasEnum {
for _, t := range typeList {
if typeStr, ok := t.(string); ok {
if typeStr == Object || typeStr == Array {
return currentDepth, v.context.RaiseErrorWithSimplify(
fmt.Sprintf("type %s is not allowed in combination with enum", typeStr),
path, SimplifyRemoveParentSchema,
)
}
}
}
}
}
}
// else {
// Empty schema {} is valid
// isAnySchema := false
// isAdditional := false
// if path.Last() == AdditionalProperties {
// isAdditional = true
// }
// if len(schema) == 0 && isAdditional {
// isAnySchema = true
// }
// if _, hasAnyOf := schema[AnyOf]; !hasAnyOf {
// if _, hasRef := schema[Ref]; !hasRef {
// if !isAnySchema {
// return currentDepth, v.context.RaiseErrorWithSimplify("type need to be defined explicitly", path, SimplifyRemoveSubSchema)
// }
// }
// }
// }
// Type keyword validation
if err := v.validateTypeAndKeywords(schema, path); err != nil {
return currentDepth, err
}
// Other keywords validation
keywords := make([]string, 0, len(schema))
for keyword := range schema {
keywords = append(keywords, keyword)
}
sort.Strings(keywords)
for _, keyword := range keywords {
value := schema[keyword]
if validator, ok := v.keywordValidators[keyword]; ok {
if err := validator(value, v.context, v.MakePath(path, keyword)); err != nil {
return currentDepth, err
}
}
}
// Check anyOf conflicts
if err := v.CheckAnyOfConflicts(schema, path); err != nil {
return currentDepth, err
}
// process $ref depth
if ref, ok := schema[Ref].(string); ok {
refDepth, exists := v.defDepths[ref]
if !exists {
refDepth = 0
}
if currentDepth+refDepth > maxDepth {
maxDepth = currentDepth + refDepth
}
}
// Recursive verify sub-schema
// properties
if props, ok := schema[Properties].(SchemaDict); ok {
propsDepth := currentDepth + 1
v.totalPropKeys += len(props)
if v.totalPropKeys > v.config.MaxTotalPropertiesKeysNum {
return currentDepth, v.context.RaiseError(
fmt.Sprintf("total number of properties keys(%d) across all objects exceeds maximum limit of %d",
v.totalPropKeys, v.config.MaxTotalPropertiesKeysNum),
path,
)
}
for propName, propSchema := range props {
propSchemaObj, ok := propSchema.(SchemaDict)
if !ok {
continue
}
depth, err := v.TraverseSchema(propSchemaObj, v.MakePath(path, Properties, propName), propsDepth)
if err != nil {
return currentDepth, err
}
if depth > maxDepth {
maxDepth = depth
}
}
}
// items
if items, ok := schema[Items].(SchemaDict); ok {
depth, err := v.TraverseSchema(items, v.MakePath(path, Items), currentDepth)
if err != nil {
return currentDepth, err
}
if depth > maxDepth {
maxDepth = depth
}
}
// additionalProperties
if addProps, ok := schema[AdditionalProperties].(SchemaDict); ok {
depth, err := v.TraverseSchema(
addProps,
v.MakePath(path, AdditionalProperties),
currentDepth,
)
if err != nil {
return currentDepth, err
}
if depth > maxDepth {
maxDepth = depth
}
}
// anyOf
if anyOf, ok := schema[AnyOf].(SchemaList); ok {
for i, subSchema := range anyOf {
subSchemaObj, ok := subSchema.(SchemaDict)
if !ok {
continue
}
depth, err := v.TraverseSchema(
subSchemaObj,
v.MakePath(path, fmt.Sprintf("anyOf{%d}", i)),
currentDepth,
)
if err != nil {
return currentDepth, err
}
if depth > maxDepth {
maxDepth = depth
}
}
}
return maxDepth, nil
}
func (v *schemaValidator) validateTypeAndKeywords(schema SchemaDict, path schemaPath) error {
if typeVal, ok := schema[Type]; ok {
var types []string
switch t := typeVal.(type) {
case string:
if !ValidTypes[t] {
return v.context.RaiseErrorWithSimplify("invalid type", path, SimplifyRemoveParentSchema)
}
types = append(types, t)
case SchemaList:
for _, item := range t {
if str, ok := item.(string); !ok || !ValidTypes[str] {
return v.context.RaiseErrorWithSimplify("invalid type in type array", path, SimplifyRemoveParentSchema)
}
types = append(types, item.(string))
}
if len(types) == 0 {
return v.context.RaiseErrorWithSimplify("type array cannot be empty", path, SimplifyRemoveParentSchema)
}
}
if len(types) > 1 {
allowedEnum := false
if len(types) == 2 && schema[Enum] != nil {
for _, t := range types {
if t == Object || t == Array {
return v.context.RaiseErrorWithSimplify("object and array cannot be used in combination with multiple types", path, SimplifyRemoveParentSchema)
}
}
allowedEnum = true
}
if v.config.IsGreaterThanStrict() {
for k := range schema {
if path.IsRoot() {
if !TopLevelOnlyKeywords[k] && !CommonKeywords[k] && k != Type && !allowedEnum {
return v.context.RaiseErrorWithSimplify(fmt.Sprintf("keyword %s is not allowed in combination with multiple types", k), path, SimplifyRemoveParentSchema)
}
} else {
if !CommonKeywords[k] && k != Type && !allowedEnum {
return v.context.RaiseErrorWithSimplify(fmt.Sprintf("keyword %s is not allowed in combination with multiple types", k), path, SimplifyRemoveParentSchema)
}
}
}
}
}
// lite only needs this for JSON-null bounds. Other mistyped or
// contradictory bounds stay strict-and-above, as they did before.
if len(types) >= 1 && (v.config.IsLite() || v.config.IsStrict()) {
if allowedKeywords, err := v.computeAllowedKeywordsForTypes(path, types); err == nil {
if err := v.validateRangeKeywordsForAllowedTypes(schema, path, allowedKeywords); err != nil {
return err
}
}
}
if len(types) >= 1 && (v.config.IsUltra() || v.config.IsTest()) {
// Check $defs and $id are only at top level
if !path.IsRoot() {
for k := range schema {
if TopLevelOnlyKeywords[k] {
return v.context.RaiseErrorWithSimplify(fmt.Sprintf("keyword %s must be at root level", k), path, SimplifyRemoveSchemaKeys([]string{k}))
}
}
}
allowedKeywords, err := v.computeAllowedKeywordsForTypes(path, types)
if err != nil {
return err
}
var invalidKeys []string
for k := range schema {
if _, exists := allowedKeywords[k]; !exists {
invalidKeys = append(invalidKeys, k)
}
}
if len(invalidKeys) > 0 {
sort.Strings(invalidKeys)
return v.context.RaiseErrorWithSimplify(
fmt.Sprintf("invalid keywords: %s", strings.Join(invalidKeys, ", ")),
path, SimplifyRemoveSchemaKeys(invalidKeys),
)
}
if err := v.validateRangeKeywordsForAllowedTypes(schema, path, allowedKeywords); err != nil {
return err
}
}
}
return nil
}
func (v *schemaValidator) computeAllowedKeywordsForTypes(path schemaPath, types []string) (map[string]struct{}, error) {
allowedKeywords := make(map[string]struct{})
if path.IsRoot() {
for k := range TopLevelOnlyKeywords {
allowedKeywords[k] = struct{}{}
}
}
if len(types) == 1 {
allowed, err := v.allowedKeywordsForSingleType(types[0], path)
if err != nil {
return nil, err
}
for k := range allowed {
allowedKeywords[k] = struct{}{}
}
return allowedKeywords, nil
}
var intersection map[string]bool
for _, schemaType := range types {
allowed, err := v.allowedKeywordsForSingleType(schemaType, path)
if err != nil {
return nil, err
}
if intersection == nil {
intersection = make(map[string]bool, len(allowed))
for k := range allowed {
intersection[k] = true
}
continue
}
for k := range intersection {
if !allowed[k] {
delete(intersection, k)
}
}
}
for k := range intersection {
allowedKeywords[k] = struct{}{}
}
return allowedKeywords, nil
}
func (v *schemaValidator) allowedKeywordsForSingleType(schemaType string, path schemaPath) (map[string]bool, error) {
switch schemaType {
case Object:
return ObjectAllowedKeywords, nil
case Array:
return ArrayAllowedKeywords, nil
case String:
return StringAllowedKeywords, nil
case Number, Integer:
return NumberAllowedKeywords, nil
case Boolean:
return BooleanAllowedKeywords, nil
case Null:
return NullAllowedKeywords, nil
default:
return nil, v.context.RaiseErrorWithSimplify(
fmt.Sprintf("invalid type: %s", schemaType),
path,
SimplifyRemoveParentSchema,
)
}
}
func (v *schemaValidator) validateRangeKeywordsForAllowedTypes(schema SchemaDict, path schemaPath, allowedKeywords map[string]struct{}) error {
_, hasMinLength := schema[MinLength]
_, hasMaxLength := schema[MaxLength]
if hasMinLength || hasMaxLength {
if _, ok := allowedKeywords[MinLength]; ok {
if err := v.validateLengthRange(schema, v.context, path); err != nil {
return err
}
}
}
_, hasMinimum := schema[Minimum]
_, hasMaximum := schema[Maximum]
if hasMinimum || hasMaximum {
if _, ok := allowedKeywords[Minimum]; ok {
if err := v.validateNumericRange(schema, v.context, path); err != nil {
return err
}
}
}
_, hasMinItems := schema[MinItems]
_, hasMaxItems := schema[MaxItems]
if hasMinItems || hasMaxItems {
if _, ok := allowedKeywords[MinItems]; ok {
if err := v.validateItemsRange(schema, v.context, path); err != nil {
return err
}
}
}
return nil
}
// Validate validates a JSON schema
func (v *schemaValidator) Validate(schema any) error {
switch s := schema.(type) {
case string:
var schemaDict SchemaDict
err := json.Unmarshal([]byte(s), &schemaDict)
if err != nil {
switch e := err.(type) {
case *json.SyntaxError:
return NewUnmarshalError(fmt.Errorf("JSON syntax error at offset %d: %s", e.Offset, e.Error()))
case *json.UnmarshalTypeError:
return NewUnmarshalError(fmt.Errorf("JSON type error at offset %d: expected %s but got %s",
e.Offset, e.Type, e.Value))
default:
return NewUnmarshalError(err)
}
}
return v.validateSchemaDict(schemaDict)
case SchemaDict:
return v.validateSchemaDict(s)
case Schema:
return v.validateSchemaDict(s)
default:
return v.context.RaiseError("input schema must be a string or map", rootSchemaPath)
}
}
func (v *schemaValidator) CanonicalWithMaxAttempts(schema Schema, maxAttempts int) (string, error) {
// Fold sibling constraints into their $ref target or anyOf branches before
// validating. Left to the retry loop these siblings would simply be deleted,
// which silently loosens the schema whenever the sibling was the stricter of
// the two. anyOf is distributed first because doing so can leave a constraint
// beside a branch's $ref, which is what the inlining pass then folds in.
inlined, droppedSiblings := inlineConflictingRefSiblings(
distributeAnyOfParentKeywords(hoistLocalRefs(schema)),
v.config.MaxSchemaSize,
)
currentSchema := Schema(inlined)
// Siblings the copy budget could not fold in were dropped in one pass rather
// than one retry at a time; surface exactly what was lost as the warning.
var rawErr error
if len(droppedSiblings) > 0 {
const maxReported = 5
shown := droppedSiblings
if len(shown) > maxReported {
shown = droppedSiblings[:maxReported]
}
rawErr = fmt.Errorf(
"inlining every $ref would exceed the schema size limit, so %d sibling constraint(s) were dropped instead: %s",
len(droppedSiblings), strings.Join(shown, ", "),
)
}
for i := 0; i < maxAttempts; i++ {
err := v.Validate(currentSchema)
if i == 0 && err != nil {
rawErr = err
}
if err == nil {
schemaStr, _ := json.Marshal(currentSchema)
return string(schemaStr), rawErr
}
if schemaErr, ok := err.(*SchemaError); ok && schemaErr.SimplifyFunc != nil {
pathObj := newSchemaPath(schemaErr.Path)
currentSchema = schemaErr.SimplifyFunc(currentSchema, pathObj)
} else {
return "{}", rawErr
}
}
return "{}", rawErr
}
func (v *schemaValidator) validateSchemaDict(schema SchemaDict) error {
// Reset state
v.Reset()
if schema == nil {
return v.context.RaiseError("schema must be a dict", rootSchemaPath)
}
// Empty schema {} is valid
if len(schema) == 0 {
return nil
}
// Callers such as chatapis Validate without Canonical. Hoist first so that
// "#/properties/..." is not rejected here by ValidateRef.
schema = hoistLocalRefs(schema)
v.context.SchemaRoot = schema
// Verify schema string length
if v.utils.CalculateSchemaSize(schema) > v.config.MaxSchemaSize {
return v.context.RaiseError("schema exceeds maximum allowed size", rootSchemaPath)
}
// Precompute defs depth
defDepths, err := v.CalculateDefDepths()
if err != nil {
return err
}
v.defDepths = defDepths
// Verify schema
maxDepth, err := v.TraverseSchema(schema, rootSchemaPath, 0)
if err != nil {
return err
}
if maxDepth > v.config.MaxSchemaDepth {
return v.context.RaiseError(fmt.Sprintf("schema depth exceeds maximum limit of %d", v.config.MaxSchemaDepth), rootSchemaPath)
}
// Verify ref path is valid
return v.PostValidateRefs()
}
// refSiblingContradiction names a keyword that the node and the schema it
// references constrain in ways that cannot both hold, or "" when they can. A
// reference that cannot be resolved is not a contradiction; PostValidateRefs
// reports that separately.
func (v *schemaValidator) refSiblingContradiction(schema SchemaDict, path schemaPath) string {
refStr, ok := schema[Ref].(string)
if !ok {
return ""
}
target, err := v.utils.ResolveRef(v.context.SchemaRoot, refStr, v.context, path)
if err != nil || target == nil {
return ""
}
return unsatisfiableOverlap(schema, target)
}
// PostValidateRefs validates all references after schema traversal
func (v *schemaValidator) PostValidateRefs() error {
// Verify all ref paths exist
for refPath := range v.context.RefPaths {
if _, err := v.utils.ResolveRef(v.context.SchemaRoot, refPath, v.context, rootSchemaPath); err != nil {
return v.context.RaiseError(fmt.Sprintf("invalid $ref path: %s", refPath), rootSchemaPath)
}
}
// Every $ref has to be able to terminate. Short-circuiting on the root was not
// enough: the root normally terminates because its own properties are optional,
// which masked non-terminating definitions nested inside $defs.
return v.TraverseAndCheckRefs(v.context.SchemaRoot, true, nil, rootSchemaPath)
}
// TraverseAndCheckRefs traverses the schema and checks all references
func (v *schemaValidator) TraverseAndCheckRefs(schema SchemaDict, needCheckTermination bool, requiredList SchemaList, path schemaPath) error {
if schema == nil {
return nil
}
if _, hasRef := schema[Ref]; hasRef {
expanded, err := v.ExpandRef(schema, make(map[string]struct{}), path)
if err != nil {
return err
}
if err := v.CheckRefContext(schema, expanded, path); err != nil {
return err
}
// Check that all refs can be terminated
if needCheckTermination {
terminates, err := v.CheckRefTermination(expanded, make(map[string]struct{}), path)
if err != nil {
return err
}
if !terminates {
return v.context.RaiseError("detected infinite recursion without termination condition", path)
}
}
}
for key, value := range schema {
if key == Defs {
continue
}
var newPath schemaPath
if path.IsRoot() {
newPath = schemaPath{Parts: []string{key}}
} else {
newPath = path.Append(key)
}
switch schemaValue := value.(type) {
case SchemaDict:
// skip some conditions that do not need to check termination
if key == Properties {
if required, ok := schema[Required]; ok {
if requiredList, ok := required.(SchemaList); ok {
if len(requiredList) == 0 {
needCheckTermination = false
}
}
}
} else if key == AdditionalProperties {
needCheckTermination = false
} else if len(requiredList) > 0 {
findRequired := false
for _, req := range requiredList {
if key == req {
findRequired = true
break
}
}
if !findRequired {
needCheckTermination = false
}
}
if err := v.TraverseAndCheckRefs(schemaValue, needCheckTermination, requiredList, newPath); err != nil {
return err
}
case SchemaList:
if key == AnyOf {
for i, item := range schemaValue {
if itemSchema, ok := item.(SchemaDict); ok {
if err := v.TraverseAndCheckRefs(
itemSchema,
needCheckTermination,
nil,
newPath.ModifyAnyOfPart(i),
); err != nil {
return err
}
}
}
}
}
}
return nil
}
// CalculateDefDepths computes the nesting depth each definition expands to.
// Like the termination check it memoizes expanded definitions -- keyed by the
// same purity rule, a depth computed without running into the path stack -- and
// gives up with an error past the shared step budget.
func (v *schemaValidator) CalculateDefDepths() (map[string]int, error) {
defDepths := make(map[string]int)
memo := make(map[string]int)
var calculateDepthsRecursive func(schema SchemaDict, currentPath string, visitedRefs map[string]struct{}) (int, bool, error)
calculateDepthsRecursive = func(schema SchemaDict, currentPath string, visitedRefs map[string]struct{}) (int, bool, error) {
v.refWalkSteps++
if v.refWalkSteps > maxRefWalkSteps {
return 0, false, v.context.RaiseError("reference graph is too complex to validate within the step budget", rootSchemaPath)
}
// The depth of basic type or empty schema is 0
if len(schema) == 0 {
return 0, false, nil
}
// Record the depth of current path
defDepths[currentPath] = 0 // Initial depth is 0
maxDepth := 0
cut := false
if ref, ok := schema[Ref].(string); ok {
if _, exists := visitedRefs[ref]; exists {
// Cycle guard: the ref contributes no depth, and the result may
// depend on the entry stack, so it must not be cached.
cut = true
} else if depth, done := memo[ref]; done {
maxDepth = depth
} else {
visitedRefs[ref] = struct{}{}
resolved, err := v.utils.ResolveRef(v.context.SchemaRoot, ref, v.context, rootSchemaPath)
if err == nil && resolved != nil {
depth, refCut, err := calculateDepthsRecursive(resolved, ref, visitedRefs)
if err != nil {
return 0, false, err
}
if !refCut {
memo[ref] = depth
}
cut = cut || refCut
maxDepth = depth
}
}
}
if props, ok := schema[Properties].(SchemaDict); ok {
propsDepth := 1
for propName, propSchema := range props {
propSchemaObj, ok := propSchema.(SchemaDict)
if !ok {
continue
}
propPath := fmt.Sprintf("%s/properties/%s", currentPath, propName)
// Create a new copy of visited refs for each property
propVisited := make(map[string]struct{})
for k, v := range visitedRefs {
propVisited[k] = v
}
subDepth, propCut, err := calculateDepthsRecursive(propSchemaObj, propPath, propVisited)
if err != nil {
return 0, false, err
}
cut = cut || propCut
if 1+subDepth > propsDepth {
propsDepth = 1 + subDepth
}
}
if propsDepth > maxDepth {
maxDepth = propsDepth
}
}
if anyOf, ok := schema[AnyOf].(SchemaList); ok {
for i, subschema := range anyOf {
subSchemaObj, ok := subschema.(SchemaDict)
if !ok {
continue
}
subPath := fmt.Sprintf("%s/anyOf/%d", currentPath, i)
// Create a new copy of visited refs for each anyOf branch
branchVisited := make(map[string]struct{})
for k, v := range visitedRefs {
branchVisited[k] = v
}
subDepth, branchCut, err := calculateDepthsRecursive(subSchemaObj, subPath, branchVisited)
if err != nil {
return 0, false, err
}
cut = cut || branchCut
if subDepth > maxDepth {
maxDepth = subDepth
}
}
}
if addProps, ok := schema[AdditionalProperties].(SchemaDict); ok {
addPropsPath := fmt.Sprintf("%s/additionalProperties", currentPath)
// Create a new copy of visited refs
addPropsVisited := make(map[string]struct{})
for k, v := range visitedRefs {
addPropsVisited[k] = v
}
subDepth, addPropsCut, err := calculateDepthsRecursive(addProps, addPropsPath, addPropsVisited)
if err != nil {
return 0, false, err
}
cut = cut || addPropsCut
if subDepth > maxDepth {
maxDepth = subDepth
}
}
// Update the final depth of current path
defDepths[currentPath] = maxDepth
return maxDepth, cut, nil
}
// Traverse from $defs
if defs, ok := v.context.SchemaRoot[Defs].(SchemaDict); ok {
for defName, defSchema := range defs {
defSchemaObj, ok := defSchema.(SchemaDict)
if !ok {
continue
}
basePath := fmt.Sprintf("#/$defs/%s", defName)
if _, _, err := calculateDepthsRecursive(defSchemaObj, basePath, make(map[string]struct{})); err != nil {
return nil, err
}
}
}
return defDepths, nil
}
// CheckRefTermination checks if a reference can be terminated
func (v *schemaValidator) CheckRefTermination(schema SchemaDict, visitedRefs map[string]struct{}, path schemaPath) (bool, error) {
// The memo is shared across every call of one validation, so a definition
// is expanded once no matter how many use sites point at it.
if v.terminationMemo == nil {