-
Notifications
You must be signed in to change notification settings - Fork 601
/
Copy pathschema.go
1243 lines (1016 loc) · 30.9 KB
/
schema.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
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
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2023-2024 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package confdb
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"github.com/snapcore/snapd/strutil"
)
type parser interface {
Schema
// expectsConstraints returns true if the parser must have a map definition
// with constraints or false, if it may have a simple name definition.
expectsConstraints() bool
// parseConstraints parses constraints for a type defined as a JSON object.
// Shouldn't be used with non-object/map type definitions.
parseConstraints(map[string]json.RawMessage) error
}
// ParseSchema parses a JSON confdb schema and returns a Schema that can be
// used to validate storage.
func ParseSchema(raw []byte) (*StorageSchema, error) {
var schemaDef map[string]json.RawMessage
err := json.Unmarshal(raw, &schemaDef)
if err != nil {
return nil, fmt.Errorf("cannot parse top level schema as map: %w", err)
}
if rawType, ok := schemaDef["type"]; ok {
var typ string
if err := json.Unmarshal(rawType, &typ); err != nil {
return nil, fmt.Errorf(`cannot parse top level schema's "type" entry: %w`, err)
}
if typ != "map" {
return nil, fmt.Errorf(`cannot parse top level schema: unexpected declared type %q, should be "map" or omitted`, typ)
}
}
if _, ok := schemaDef["schema"]; !ok {
return nil, fmt.Errorf(`cannot parse top level schema: must have a "schema" constraint`)
}
schema := new(StorageSchema)
if aliasesRaw, ok := schemaDef["aliases"]; ok {
var aliases map[string]json.RawMessage
if err := json.Unmarshal(aliasesRaw, &aliases); err != nil {
return nil, fmt.Errorf(`cannot parse aliases map: %w`, err)
}
// TODO: if we want to allow aliases to refer to others, this must be handled
// explicitly since the "aliases" map doesn't have any implicit order
schema.aliases = make(map[string]*aliasRefParser, len(aliases))
for alias, typeDef := range aliases {
if !validAliasName.Match([]byte(alias)) {
return nil, fmt.Errorf(`cannot parse alias name %q: must match %s`, alias, validAliasName)
}
aliasSchema, err := schema.parse(typeDef)
if err != nil {
return nil, fmt.Errorf(`cannot parse alias %q: %w`, alias, err)
}
schema.aliases[alias] = newAliasRefParser(aliasSchema)
}
}
schema.topLevel, err = schema.parse(raw)
if err != nil {
return nil, err
}
return schema, nil
}
// aliasRefParser parses references to aliases (e.g., $my-type).
type aliasRefParser struct {
Schema
stringBased bool
}
func newAliasRefParser(s Schema) *aliasRefParser {
_, ok := s.(*stringSchema)
return &aliasRefParser{
Schema: s,
stringBased: ok,
}
}
// expectsConstraints return false because a reference to an alias doesn't
// define constraints (these are defined under "aliases" at the top level).
func (*aliasRefParser) expectsConstraints() bool {
return false
}
// parseConstraints is a no-op because type references can't define constraints.
func (v *aliasRefParser) parseConstraints(map[string]json.RawMessage) error {
return nil
}
// isStringBased returns true if this reference's base type is a string.
func (u *aliasRefParser) isStringBased() bool {
return u.stringBased
}
// StorageSchema represents a confdb schema and can be used to validate the
// storage.
type StorageSchema struct {
// topLevel is the schema for the top level map.
topLevel Schema
// aliases are schemas that can validate custom types defined by the user.
aliases map[string]*aliasRefParser
}
// Validate validates the provided JSON object.
func (s *StorageSchema) Validate(raw []byte) error {
return s.topLevel.Validate(raw)
}
// SchemaAt returns the types that may be stored at the specified path.
func (s *StorageSchema) SchemaAt(path []string) ([]Schema, error) {
return s.topLevel.SchemaAt(path)
}
func (s *StorageSchema) Type() SchemaType {
return s.topLevel.Type()
}
func (s *StorageSchema) parse(raw json.RawMessage) (Schema, error) {
jsonType, err := parseTypeDefinition(raw)
if err != nil {
return nil, fmt.Errorf(`cannot parse type definition: %w`, err)
}
var typ string
var schemaDef map[string]json.RawMessage
switch typedVal := jsonType.(type) {
case string:
typ = typedVal
case []json.RawMessage:
alts, err := s.parseAlternatives(typedVal)
if err != nil {
return nil, fmt.Errorf(`cannot parse alternative types: %w`, err)
}
return alts, nil
case map[string]json.RawMessage:
schemaDef = typedVal
rawType, ok := schemaDef["type"]
if !ok {
typ = "map"
} else {
if err := json.Unmarshal(rawType, &typ); err != nil {
return nil, fmt.Errorf(`cannot parse "type" constraint in type definition: %w`, err)
}
}
default:
// cannot happen save for programmer error
return nil, fmt.Errorf(`cannot parse schema definition of JSON type %T`, jsonType)
}
schema, err := s.newTypeSchema(typ)
if err != nil {
return nil, err
}
// only parse the schema if it's a schema definition w/ constraints
if schemaDef != nil {
if err := schema.parseConstraints(schemaDef); err != nil {
return nil, err
}
} else if schema.expectsConstraints() {
return nil, fmt.Errorf(`cannot parse %q: must be schema definition with constraints`, typ)
}
return schema, nil
}
// parseTypeDefinition tries to parse the raw JSON as a list, a map or a string
// (the accepted ways to express types).
func parseTypeDefinition(raw json.RawMessage) (interface{}, error) {
var typeErr *json.UnmarshalTypeError
var l []json.RawMessage
if err := json.Unmarshal(raw, &l); err == nil {
return l, nil
} else if !errors.As(err, &typeErr) {
return nil, err
}
var m map[string]json.RawMessage
if err := json.Unmarshal(raw, &m); err == nil {
return m, nil
} else if !errors.As(err, &typeErr) {
return nil, err
}
var s string
if err := json.Unmarshal(raw, &s); err == nil {
return s, nil
} else {
return nil, fmt.Errorf(`type must be expressed as map, string or list: %w`, err)
}
}
// parseAlternatives takes a list of alternative types, parses them and creates
// a schema that accepts values matching any alternative.
func (s *StorageSchema) parseAlternatives(alternatives []json.RawMessage) (*alternativesSchema, error) {
alt := &alternativesSchema{schemas: make([]Schema, 0, len(alternatives))}
for _, altRaw := range alternatives {
schema, err := s.parse(altRaw)
if err != nil {
return nil, err
}
alt.schemas = append(alt.schemas, schema)
}
if len(alt.schemas) == 0 {
return nil, fmt.Errorf(`alternative type list cannot be empty`)
}
flatAlts := flattenAlternatives(alt)
alt.schemas = flatAlts
return alt, nil
}
// flattenAlternatives takes the schemas that comprise the alternative schema
// and flattens them into a single list.
func flattenAlternatives(alt *alternativesSchema) []Schema {
var flat []Schema
for _, schema := range alt.schemas {
if altSchema, ok := schema.(*alternativesSchema); ok {
nestedAlts := flattenAlternatives(altSchema)
flat = append(flat, nestedAlts...)
} else {
flat = append(flat, schema)
}
}
return flat
}
func (s *StorageSchema) newTypeSchema(typ string) (parser, error) {
switch typ {
case "map":
return &mapSchema{topSchema: s}, nil
case "string":
return &stringSchema{}, nil
case "int":
return &intSchema{}, nil
case "any":
return &anySchema{}, nil
case "number":
return &numberSchema{}, nil
case "bool":
return &booleanSchema{}, nil
case "array":
return &arraySchema{topSchema: s}, nil
default:
if typ != "" && typ[0] == '$' {
return s.getAlias(typ[1:])
}
return nil, fmt.Errorf("cannot parse unknown type %q", typ)
}
}
func (s *StorageSchema) getAlias(ref string) (*aliasRefParser, error) {
if alias, ok := s.aliases[ref]; ok {
return alias, nil
}
return nil, fmt.Errorf("cannot find alias %q", ref)
}
type alternativesSchema struct {
// schemas holds schemas for the types allowed for the corresponding value.
schemas []Schema
}
// Validate that raw matches at least one of the schemas in the alternative list.
func (v *alternativesSchema) Validate(raw []byte) error {
var errs []error
for _, schema := range v.schemas {
err := schema.Validate(raw)
if err == nil {
return nil
}
errs = append(errs, err)
}
var sb strings.Builder
sb.WriteString("no matching schema:")
for i, err := range errs {
sb.WriteString("\n\t")
if i > 0 {
sb.WriteString("or ")
}
if verr, ok := err.(*ValidationError); ok {
err = verr.Err
if len(verr.Path) != 0 {
sb.WriteString("...\"")
for i, part := range verr.Path {
switch v := part.(type) {
case string:
if i > 0 {
sb.WriteRune('.')
}
sb.WriteString(v)
case int:
sb.WriteString(fmt.Sprintf("[%d]", v))
default:
// can only happen due to bug
sb.WriteString(".<n/a>")
}
}
sb.WriteString("\": ")
}
}
sb.WriteString(err.Error())
}
return validationErrorFrom(errors.New(sb.String()))
}
// SchemaAt returns the list of schemas at the end of the path or an error if
// the path cannot be followed.
func (v *alternativesSchema) SchemaAt(path []string) ([]Schema, error) {
if len(path) == 0 {
return v.schemas, nil
}
var types []Schema
var lastErr error
for _, alt := range v.schemas {
altTypes, err := alt.SchemaAt(path)
if err != nil {
// some schemas may permit the path
lastErr = err
continue
}
types = append(types, altTypes...)
}
// TODO: find better way to combine errors
if len(types) == 0 {
return nil, lastErr
}
return types, nil
}
func (v *alternativesSchema) Type() SchemaType {
return Alt
}
type mapSchema struct {
// topSchema is the schema for the top-level schema which contains the aliases.
topSchema *StorageSchema
// entrySchemas maps keys to their expected types. Alternatively, the schema
// can constrain key and/or value types.
entrySchemas map[string]Schema
// valueSchema validates that the map's values match a certain type.
valueSchema Schema
// keySchema validates that the map's key match a certain type.
keySchema Schema
// requiredCombs holds combinations of keys that an instance of the map is
// allowed to have.
requiredCombs [][]string
}
// Validate that raw is a valid map and meets the constraints set by the
// confdb schema.
func (v *mapSchema) Validate(raw []byte) error {
var mapValue map[string]json.RawMessage
if err := json.Unmarshal(raw, &mapValue); err != nil {
typeErr := &json.UnmarshalTypeError{}
if errors.As(err, &typeErr) {
return validationErrorf("expected map type but value was %s", typeErr.Value)
}
return validationErrorFrom(err)
}
if mapValue == nil {
return validationErrorf(`cannot accept null value for "map" type`)
}
if err := validMapKeys(mapValue); err != nil {
return validationErrorFrom(err)
}
if v.entrySchemas != nil {
for key := range mapValue {
if _, ok := v.entrySchemas[key]; !ok {
return validationErrorf(`map contains unexpected key %q`, key)
}
}
}
var missing bool
for _, required := range v.requiredCombs {
missing = false
for _, key := range required {
if _, ok := mapValue[key]; !ok {
missing = true
break
}
}
if !missing {
// matched possible combination of required keys so we can stop
break
}
}
if missing {
return validationErrorf(`cannot find required combinations of keys`)
}
if v.entrySchemas != nil {
for key, val := range mapValue {
if validator, ok := v.entrySchemas[key]; ok {
if err := validator.Validate(val); err != nil {
var valErr *ValidationError
if errors.As(err, &valErr) {
valErr.Path = append([]interface{}{key}, valErr.Path...)
}
return err
}
}
}
// all required entries are present and validated
return nil
}
if v.keySchema != nil {
for k := range mapValue {
rawKey, err := json.Marshal(k)
if err != nil {
return fmt.Errorf("internal error: %w", err)
}
if err := v.keySchema.Validate(rawKey); err != nil {
var valErr *ValidationError
if errors.As(err, &valErr) {
valErr.Path = append([]interface{}{k}, valErr.Path...)
}
return err
}
}
}
if v.valueSchema != nil {
for k, val := range mapValue {
if err := v.valueSchema.Validate(val); err != nil {
var valErr *ValidationError
if errors.As(err, &valErr) {
valErr.Path = append([]interface{}{k}, valErr.Path...)
}
return err
}
}
}
return nil
}
func validMapKeys(v map[string]json.RawMessage) error {
for k := range v {
if !validSubkey.Match([]byte(k)) {
return fmt.Errorf(`key %q doesn't conform to required format: %s`, k, validSubkey.String())
}
}
return nil
}
// SchemaAt returns the Map schema if this is the last path element. If not, it
// calls SchemaAt for the next path element's schema if the path is valid.
func (v *mapSchema) SchemaAt(path []string) ([]Schema, error) {
if len(path) == 0 {
return []Schema{v}, nil
}
key := path[0]
if v.entrySchemas != nil {
valSchema, ok := v.entrySchemas[key]
if !ok {
return nil, schemaAtErrorf(path, `cannot use %q as key in map`, key)
}
return valSchema.SchemaAt(path[1:])
}
return v.valueSchema.SchemaAt(path[1:])
}
// Type returns the Map type.
func (v *mapSchema) Type() SchemaType {
return Map
}
func (v *mapSchema) parseConstraints(constraints map[string]json.RawMessage) error {
err := checkExclusiveMapConstraints(constraints)
if err != nil {
return fmt.Errorf(`cannot parse map: %w`, err)
}
// maps can be "schemas" with types for specific entries and optional "required" constraints
if rawEntries, ok := constraints["schema"]; ok {
var entries map[string]json.RawMessage
if err := json.Unmarshal(rawEntries, &entries); err != nil {
return fmt.Errorf(`cannot parse map's "schema" constraint: %v`, err)
}
if err := validMapKeys(entries); err != nil {
return fmt.Errorf(`cannot parse map: %w`, err)
}
v.entrySchemas = make(map[string]Schema, len(entries))
for key, value := range entries {
entrySchema, err := v.topSchema.parse(value)
if err != nil {
return err
}
v.entrySchemas[key] = entrySchema
}
// "required" can be a list of keys or many lists of alternative combinations
if rawRequired, ok := constraints["required"]; ok {
var requiredCombs [][]string
if err := json.Unmarshal(rawRequired, &requiredCombs); err != nil {
var typeErr *json.UnmarshalTypeError
if !errors.As(err, &typeErr) {
return fmt.Errorf(`cannot parse map's "required" constraint: %v`, err)
}
var required []string
if err := json.Unmarshal(rawRequired, &required); err != nil {
return fmt.Errorf(`cannot parse map's "required" constraint: %v`, err)
}
v.requiredCombs = [][]string{required}
} else {
v.requiredCombs = requiredCombs
}
for _, requiredComb := range v.requiredCombs {
for _, required := range requiredComb {
if _, ok := v.entrySchemas[required]; !ok {
return fmt.Errorf(`cannot parse map's "required" constraint: required key %q must have schema entry`, required)
}
}
}
}
return nil
}
// map can not specify "schemas" and constrain the type of keys and values instead
rawKeyDef, ok := constraints["keys"]
if ok {
if v.keySchema, err = v.parseMapKeyType(rawKeyDef); err != nil {
return fmt.Errorf(`cannot parse "keys" constraint: %w`, err)
}
}
rawValuesDef, ok := constraints["values"]
if ok {
v.valueSchema, err = v.topSchema.parse(rawValuesDef)
if err != nil {
return err
}
}
if v.entrySchemas == nil && v.keySchema == nil && v.valueSchema == nil {
return fmt.Errorf(`cannot parse map: must have "schema" or "keys"/"values" constraint`)
}
return nil
}
// checkExclusiveMapConstraints checks if the map contains mutually exclusive constraints.
func checkExclusiveMapConstraints(obj map[string]json.RawMessage) error {
has := func(k string) bool {
_, ok := obj[k]
return ok
}
if has("required") && !has("schema") {
return fmt.Errorf(`cannot use "required" without "schema" constraint`)
}
if has("schema") && has("keys") {
return fmt.Errorf(`cannot use "schema" and "keys" constraints simultaneously`)
}
if has("schema") && has("values") {
return fmt.Errorf(`cannot use "schema" and "values" constraints simultaneously`)
}
return nil
}
func (v *mapSchema) parseMapKeyType(raw json.RawMessage) (Schema, error) {
var typ string
if err := json.Unmarshal(raw, &typ); err != nil {
var typeErr *json.UnmarshalTypeError
if !errors.As(err, &typeErr) {
return nil, err
}
var schemaDef map[string]json.RawMessage
if err := json.Unmarshal(raw, &schemaDef); err != nil {
return nil, err
}
if rawType, ok := schemaDef["type"]; ok {
if err := json.Unmarshal(rawType, &typ); err != nil {
return nil, err
}
if typ != "string" {
return nil, fmt.Errorf(`must be based on string but type was %s`, typ)
}
}
schema := &stringSchema{}
if err := schema.parseConstraints(schemaDef); err != nil {
return nil, err
}
return schema, nil
}
if typ == "string" {
return &stringSchema{}, nil
}
if typ != "" && typ[0] == '$' {
alias, err := v.topSchema.getAlias(typ[1:])
if err != nil {
return nil, err
}
if !alias.isStringBased() {
return nil, fmt.Errorf(`key type %q must be based on string`, typ[1:])
}
return alias, nil
}
return nil, fmt.Errorf(`keys must be based on string but type was %s`, typ)
}
func (v *mapSchema) expectsConstraints() bool { return true }
type stringSchema struct {
// pattern is a regex pattern that the string must match.
pattern *regexp.Regexp
// choices holds the possible values the string can take, if non-empty.
choices []string
}
// Validate that raw is a valid string and meets the schema's constraints.
func (v *stringSchema) Validate(raw []byte) (err error) {
defer func() {
if err != nil {
err = validationErrorFrom(err)
}
}()
var value *string
if err := json.Unmarshal(raw, &value); err != nil {
typeErr := &json.UnmarshalTypeError{}
if errors.As(err, &typeErr) {
return fmt.Errorf("expected string type but value was %s", typeErr.Value)
}
return err
}
if value == nil {
return fmt.Errorf(`cannot accept null value for "string" type`)
}
if len(v.choices) != 0 && !strutil.ListContains(v.choices, *value) {
return fmt.Errorf(`string %q is not one of the allowed choices`, *value)
}
if v.pattern != nil && !v.pattern.Match([]byte(*value)) {
return fmt.Errorf(`expected string matching %s but value was %q`, v.pattern.String(), *value)
}
return nil
}
// SchemaAt returns the string schema if the path terminates at this schema and
// an error if not.
func (v *stringSchema) SchemaAt(path []string) ([]Schema, error) {
if len(path) != 0 {
return nil, schemaAtErrorf(path, `cannot follow path beyond "string" type`)
}
return []Schema{v}, nil
}
func (v *stringSchema) Type() SchemaType {
return String
}
func (v *stringSchema) parseConstraints(constraints map[string]json.RawMessage) error {
if rawChoices, ok := constraints["choices"]; ok {
var choices []string
if err := json.Unmarshal(rawChoices, &choices); err != nil {
return fmt.Errorf(`cannot parse "choices" constraint: %w`, err)
}
if len(choices) == 0 {
return fmt.Errorf(`cannot have a "choices" constraint with an empty list`)
}
v.choices = choices
}
if rawPattern, ok := constraints["pattern"]; ok {
if v.choices != nil {
return fmt.Errorf(`cannot use "choices" and "pattern" constraints in same schema`)
}
var patt string
err := json.Unmarshal(rawPattern, &patt)
if err != nil {
return fmt.Errorf(`cannot parse "pattern" constraint: %w`, err)
}
if v.pattern, err = regexp.Compile(patt); err != nil {
return fmt.Errorf(`cannot parse "pattern" constraint: %w`, err)
}
}
return nil
}
func (v *stringSchema) expectsConstraints() bool { return false }
type intSchema struct {
min *int64
max *int64
choices []int64
}
// Validate that raw is a valid integer and meets the schema's constraints.
func (v *intSchema) Validate(raw []byte) (err error) {
defer func() {
if err != nil {
err = validationErrorFrom(err)
}
}()
var num *int64
if err := json.Unmarshal(raw, &num); err != nil {
typeErr := &json.UnmarshalTypeError{}
if errors.As(err, &typeErr) {
return fmt.Errorf("expected int type but value was %s", typeErr.Value)
}
return err
}
if num == nil {
return fmt.Errorf(`cannot accept null value for "int" type`)
}
return validateNumber(*num, v.choices, v.min, v.max)
}
// SchemaAt returns the int schema if the path terminates here and an error if
// not.
func (v *intSchema) SchemaAt(path []string) ([]Schema, error) {
if len(path) != 0 {
return nil, schemaAtErrorf(path, `cannot follow path beyond "int" type`)
}
return []Schema{v}, nil
}
// Type returns the Int schema type.
func (v *intSchema) Type() SchemaType {
return Int
}
func (v *intSchema) parseConstraints(constraints map[string]json.RawMessage) error {
if rawChoices, ok := constraints["choices"]; ok {
var choices []int64
err := json.Unmarshal(rawChoices, &choices)
if err != nil {
return fmt.Errorf(`cannot parse "choices" constraint: %v`, err)
}
if len(choices) == 0 {
return fmt.Errorf(`cannot have "choices" constraint with empty list`)
}
v.choices = choices
}
if rawMin, ok := constraints["min"]; ok {
if v.choices != nil {
return fmt.Errorf(`cannot have "choices" and "min" constraints`)
}
var min int64
if err := json.Unmarshal(rawMin, &min); err != nil {
return fmt.Errorf(`cannot parse "min" constraint: %v`, err)
}
v.min = &min
}
if rawMax, ok := constraints["max"]; ok {
if v.choices != nil {
return fmt.Errorf(`cannot have "choices" and "max" constraints`)
}
var max int64
if err := json.Unmarshal(rawMax, &max); err != nil {
return fmt.Errorf(`cannot parse "max" constraint: %v`, err)
}
v.max = &max
}
if v.min != nil && v.max != nil && *v.min > *v.max {
return fmt.Errorf(`cannot have "min" constraint with value greater than "max"`)
}
return nil
}
func (v *intSchema) expectsConstraints() bool { return false }
type anySchema struct{}
func (v *anySchema) Validate(raw []byte) (err error) {
defer func() {
if err != nil {
err = validationErrorFrom(err)
}
}()
var val interface{}
if err := json.Unmarshal(raw, &val); err != nil {
return err
}
if val == nil {
return fmt.Errorf(`cannot accept null value for "any" type`)
}
return nil
}
func (v *anySchema) parseConstraints(map[string]json.RawMessage) error {
// no error because we're not explicitly rejecting unsupported keywords (for now)
return nil
}
// SchemaAt returns the "any" schema.
func (v *anySchema) SchemaAt([]string) ([]Schema, error) {
return []Schema{v}, nil
}
// Type returns the Any schema type.
func (v *anySchema) Type() SchemaType {
return Any
}
func (v *anySchema) expectsConstraints() bool { return false }
type numberSchema struct {
min *float64
max *float64
choices []float64
}
// Validate that raw is a valid number and meets the schema's constraints.
func (v *numberSchema) Validate(raw []byte) (err error) {
defer func() {
if err != nil {
err = validationErrorFrom(err)
}
}()
var num *float64
if err := json.Unmarshal(raw, &num); err != nil {
typeErr := &json.UnmarshalTypeError{}
if errors.As(err, &typeErr) {
return fmt.Errorf("expected number type but value was %s", typeErr.Value)
}
return err
}
if num == nil {
return fmt.Errorf(`cannot accept null value for "number" type`)
}
return validateNumber(*num, v.choices, v.min, v.max)
}
// SchemaAt returns the number schema if the path terminates here and an error if
// not.
func (v *numberSchema) SchemaAt(path []string) ([]Schema, error) {
if len(path) != 0 {
return nil, schemaAtErrorf(path, `cannot follow path beyond "number" type`)
}
return []Schema{v}, nil
}
// Type returns the Number schema type.
func (v *numberSchema) Type() SchemaType {
return Number
}
func validateNumber[Num ~int64 | ~float64](num Num, choices []Num, min, max *Num) error {
if len(choices) != 0 {
var found bool
for _, choice := range choices {
if num == choice {
found = true
break
}
}
if !found {
return fmt.Errorf(`%v is not one of the allowed choices`, num)
}
}
// these comparisons are susceptible to floating-point errors but given that
// this won't be used for general storage it should be precise enough
if min != nil && num < *min {
return fmt.Errorf(`%v is less than the allowed minimum %v`, num, *min)
}
if max != nil && num > *max {
return fmt.Errorf(`%v is greater than the allowed maximum %v`, num, *max)
}
return nil
}
func (v *numberSchema) parseConstraints(constraints map[string]json.RawMessage) error {
if rawChoices, ok := constraints["choices"]; ok {
var choices []float64
err := json.Unmarshal(rawChoices, &choices)
if err != nil {
return fmt.Errorf(`cannot parse "choices" constraint: %v`, err)
}
if len(choices) == 0 {
return fmt.Errorf(`cannot have "choices" constraint with empty list`)
}