/
validate.go
662 lines (626 loc) · 16.7 KB
/
validate.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
package dynaml
import (
"fmt"
"github.com/mandelsoft/spiff/yaml"
"net"
"regexp"
"strings"
)
type Validator func(value interface{}, binding Binding, args ...interface{}) (bool, string, error, bool)
var validators = map[string]Validator{}
func RegisterValidator(name string, f Validator) {
validators[name] = f
}
func func_validate(arguments []interface{}, binding Binding) (bool, interface{}, EvaluationInfo, bool) {
info := DefaultInfo()
if len(arguments) < 2 {
info.Error("at least two arguments required for validate")
return true, nil, info, false
}
value := arguments[0]
for i, c := range arguments[1:] {
r, m, err, ok := EvalValidationExpression(value, NewNode(c, binding), binding)
if err != nil {
info.SetError("condition %d has problem: %s", i+1, err)
return true, nil, info, false
}
if !ok {
return false, nil, info, true
}
if !r {
info.SetError("condition %d failed: %s", i+1, m)
return true, nil, info, false
}
}
return true, value, info, true
}
func func_check(arguments []interface{}, binding Binding) (bool, interface{}, EvaluationInfo, bool) {
info := DefaultInfo()
if len(arguments) < 2 {
info.Error("at least two arguments required for check")
return true, nil, info, false
}
value := arguments[0]
for i, c := range arguments[1:] {
r, _, err, ok := EvalValidationExpression(value, NewNode(c, binding), binding)
if err != nil {
info.SetError("condition %d has problem: %s", i+1, err)
return true, nil, info, false
}
if !ok {
return false, nil, info, true
}
if !r {
return true, false, info, true
}
}
return true, true, info, true
}
// first result: validation successful
// second: message
// third: condition error
// fourth: expression already resolved
func EvalValidationExpression(value interface{}, cond yaml.Node, binding Binding) (bool, string, error, bool) {
if cond == nil || cond.Value() == nil {
return ValidatorResult(true, "no condition")
}
switch v := cond.Value().(type) {
case string:
return _validate(value, v, binding)
case LambdaValue:
return _validate(value, v, binding)
case []yaml.Node:
if len(v) == 0 {
return ValidatorErrorf("validation type missing")
}
return _validate(value, v[0].Value(), binding, v[1:]...)
default:
return ValidatorErrorf("invalid validation check type: %s", ExpressionType(v))
}
}
func _validate(value interface{}, cond interface{}, binding Binding, args ...yaml.Node) (bool, string, error, bool) {
var err error
switch v := cond.(type) {
case LambdaValue:
if len(v.lambda.Parameters) != len(args)+1 {
return ValidatorErrorf("argument count mismatch for lambda %s: expected %d, found %d", v, len(v.lambda.Parameters), len(args)+1)
}
vargs := []interface{}{value}
for _, a := range args {
vargs = append(vargs, a.Value())
}
valid, r, info, ok := v.Evaluate(false, false, false, nil, vargs, binding, false)
if !valid {
if !ok {
err = fmt.Errorf("%s", info.Issue.Issue)
}
return false, "", err, false
}
l, ok := r.([]yaml.Node)
if ok {
switch len(l) {
case 1:
r = l[0].Value()
break
case 2:
t, err := StringValue("lambda validator", l[1].Value())
if err != nil {
return ValidatorErrorf("lambda validator result index %d: %s", 2, err)
}
return toBool(l[0].Value()), t, nil, true
case 3:
t, err := StringValue("lambda validator", l[1].Value())
if err != nil {
return ValidatorErrorf("lambda validator result index %d: %s", 2, err)
}
f, err := StringValue("lambda validator", l[2].Value())
if err != nil {
return ValidatorErrorf("lambda validator result index %d: %s", 3, err)
}
return SimpleValidatorResult(toBool(l[0].Value()), t, f)
default:
return ValidatorErrorf("invalid result length of validator %s, got %d", v, len(l))
}
}
return SimpleValidatorResult(toBool(r), fmt.Sprintf("%s succeeded", v), "%s failed", v)
case string:
not := strings.HasPrefix(v, "!")
if not {
v = v[1:]
} else {
if v == "" {
return ValidatorErrorf("empty validator type")
}
}
if v == "not" {
not = !not
}
r, m, err, resolved := handleStringType(value, v, binding, args...)
if !resolved || err != nil {
return false, "", err, resolved
}
if not {
return !r, m, err, resolved
} else {
return r, m, err, resolved
}
default:
return ValidatorErrorf("unexpected validation type %q", ExpressionType(v))
}
}
func handleStringType(value interface{}, op string, binding Binding, args ...yaml.Node) (bool, string, error, bool) {
reason := "("
optional := false
switch op {
case "list":
l, ok := value.([]yaml.Node)
if !ok {
return ValidatorResult(false, "is no list")
}
if len(args) == 0 {
return ValidatorResult(true, "is a list")
}
for i, e := range l {
for j, c := range args {
r, m, err, valid := EvalValidationExpression(e.Value(), c, binding)
if err != nil {
return ValidatorErrorf("list entry %d condition %d: %s", i, j, err)
}
if !valid {
return false, "", nil, false
}
if !r {
return ValidatorResult(false, "entry %d condition %d %s", i, j, m)
}
}
}
return ValidatorResult(true, "all entries match all conditions")
case "map":
l, ok := value.(map[string]yaml.Node)
if !ok {
return ValidatorResult(false, "is no map")
}
if len(args) == 0 {
return ValidatorResult(true, "is a map")
}
var ck yaml.Node
if len(args) > 2 {
return ValidatorErrorf("map validator takes a maximum of two arguments, got %d", len(args))
}
if len(args) == 2 {
ck = args[0]
}
ce := args[len(args)-1]
for k, e := range l {
if ck != nil {
r, m, err, valid := EvalValidationExpression(k, ck, binding)
if err != nil {
return ValidatorErrorf("map key %q %s", k, err)
}
if !valid {
return false, "", nil, false
}
if !r {
return ValidatorResult(false, "map key %q %s", k, m)
}
}
r, m, err, valid := EvalValidationExpression(e.Value(), ce, binding)
if err != nil {
return ValidatorErrorf("map entry %q: %s", k, err)
}
if !valid {
return false, "", nil, false
}
if !r {
return ValidatorResult(false, "map entry %q %s", k, m)
}
}
return ValidatorResult(true, "all map entries and keys match")
case "optionalfield":
optional = true
fallthrough
case "mapfield":
l, ok := value.(map[string]yaml.Node)
if !ok {
return ValidatorResult(false, "is no map")
}
if len(args) < 1 || len(args) > 2 {
return ValidatorErrorf("%s reqires one or two arguments", op)
}
field, err := StringValue(op, args[0].Value())
if err != nil {
return ValidatorErrorf("field name must be string")
}
val, ok := l[field]
if !ok {
if optional {
return ValidatorResult(true, "has no optional field %q", field)
}
return ValidatorResult(false, "has no field %q", field)
}
if len(args) == 2 {
r, m, err, valid := EvalValidationExpression(val.Value(), args[1], binding)
if err != nil {
return ValidatorErrorf("map entry %q %s", field, err)
}
if !valid {
return false, "", nil, false
}
return ValidatorResult(r, "map entry %q %s", field, m)
}
return ValidatorResult(true, "map entry %q exists", field)
case "and", "not", "":
if len(args) == 0 {
return ValidatorErrorf("validator argument required")
}
for _, c := range args {
r, m, err, resolved := EvalValidationExpression(value, c, binding)
if err != nil || !resolved {
return false, "", err, resolved
}
if reason != "(" {
reason += " and "
}
reason += m
if !r {
return ValidatorResult(false, m)
}
}
if len(args) == 1 {
return ValidatorResult(true, reason[1:])
}
return ValidatorResult(true, reason+")")
case "or":
if len(args) == 0 {
return ValidatorErrorf("validator argument required")
}
for _, c := range args {
r, m, err, resolved := EvalValidationExpression(value, c, binding)
if err != nil || !resolved {
return false, "", err, resolved
}
if reason != "(" {
reason += " and "
}
reason += m
if r {
return ValidatorResult(true, m)
}
}
if len(args) == 1 {
return ValidatorResult(true, reason[1:])
}
return ValidatorResult(false, reason+")")
case "empty":
switch v := value.(type) {
case string:
return SimpleValidatorResult(v == "", "is empty", "is not empty")
case []yaml.Node:
return SimpleValidatorResult(len(v) == 0, "is empty", "is not empty")
case map[string]yaml.Node:
return SimpleValidatorResult(len(v) == 0, "is empty", "is not empty")
default:
return ValidatorErrorf("invalid type for empty: %s", ExpressionType(v))
}
case "valueset":
if len(args) != 1 {
return ValidatorErrorf("valueset requires a list argument with possible values")
}
l, ok := args[0].Value().([]yaml.Node)
if !ok {
return ValidatorErrorf("valueset requires a list argument with possible values")
}
for _, v := range l {
if ok, _, _ := compareEquals(value, v.Value()); ok {
return ValidatorResult(true, "matches valueset")
}
}
s, ok := value.(string)
if ok {
return ValidatorResult(false, "invalid value %q", s)
}
i, ok := value.(int64)
if ok {
return ValidatorResult(false, "invalid value %d", i)
}
return ValidatorResult(false, "invalid value")
case "value", "=":
if len(args) != 1 {
return ValidatorErrorf("value requires a value argument")
}
s := args[0].Value()
sv, isStr := value.(string)
if ok, _, _ := compareEquals(s, value); !ok {
if isStr {
return ValidatorResult(false, "invalid value %q", sv)
}
return ValidatorResult(false, "invalid value")
}
if isStr {
return ValidatorResult(true, "valid value %q", sv)
}
return ValidatorResult(true, "valid value")
case "gt", ">":
if len(args) != 1 {
return ValidatorErrorf("gt requires a value argument")
}
s := args[0].Value()
r := false
switch cv := s.(type) {
case string:
s, ok := value.(string)
if !ok {
return ValidatorErrorf("must be string to compare to string")
}
r = strings.Compare(s, cv) > 0
case int64:
s, ok := value.(int64)
if !ok {
s, ok := value.(float64)
if !ok {
return ValidatorErrorf("must be number to compare to number")
}
r = s > float64(cv)
} else {
r = s > cv
}
case float64:
s, ok := value.(int64)
if !ok {
s, ok := value.(float64)
if !ok {
return ValidatorErrorf("must be number to compare to number")
}
r = s > cv
} else {
r = float64(s) > cv
}
default:
return ValidatorErrorf("invalid type %T", s)
}
if !r {
return ValidatorResult(false, "less or equal to %v", s)
}
return ValidatorResult(true, "greater than %v", s)
case "lt", "<":
if len(args) != 1 {
return ValidatorErrorf("lt requires a value argument")
}
s := args[0].Value()
r := false
switch cv := s.(type) {
case string:
s, ok := value.(string)
if !ok {
return ValidatorErrorf("must be string to compare to string")
}
r = strings.Compare(s, cv) < 0
case int64:
s, ok := value.(int64)
if !ok {
s, ok := value.(float64)
if !ok {
return ValidatorErrorf("must be number to compare to number")
}
r = s < float64(cv)
} else {
r = s < cv
}
case float64:
s, ok := value.(int64)
if !ok {
s, ok := value.(float64)
if !ok {
return ValidatorErrorf("must be number to compare to number")
}
r = s < cv
} else {
r = float64(s) < cv
}
default:
return ValidatorErrorf("invalid type %T", s)
}
if !r {
return ValidatorResult(false, "greater than %v", s)
}
return ValidatorResult(true, "less or equal to %v", s)
case "ge", ">=":
if len(args) != 1 {
return ValidatorErrorf("ge requires a value argument")
}
s := args[0].Value()
r := false
switch cv := s.(type) {
case string:
s, ok := value.(string)
if !ok {
return ValidatorErrorf("must be string to compare to string")
}
r = strings.Compare(s, cv) >= 0
case int64:
s, ok := value.(int64)
if !ok {
s, ok := value.(float64)
if !ok {
return ValidatorErrorf("must be number to compare to number")
}
r = s >= float64(cv)
} else {
r = s >= cv
}
case float64:
s, ok := value.(int64)
if !ok {
s, ok := value.(float64)
if !ok {
return ValidatorErrorf("must be number to compare to number")
}
r = s >= cv
} else {
r = float64(s) >= cv
}
default:
return ValidatorErrorf("invalid type %T", s)
}
if !r {
return ValidatorResult(false, "less than %v", s)
}
return ValidatorResult(true, "greater or equal to %v", s)
case "le", "<=":
if len(args) != 1 {
return ValidatorErrorf("lt requires a value argument")
}
s := args[0].Value()
r := false
switch cv := s.(type) {
case string:
s, ok := value.(string)
if !ok {
return ValidatorErrorf("must be string to compare to string")
}
r = strings.Compare(s, cv) <= 0
case int64:
s, ok := value.(int64)
if !ok {
s, ok := value.(float64)
if !ok {
return ValidatorErrorf("must be number to compare to number")
}
r = s <= float64(cv)
} else {
r = s <= cv
}
case float64:
s, ok := value.(int64)
if !ok {
s, ok := value.(float64)
if !ok {
return ValidatorErrorf("must be number to compare to number")
}
r = s <= cv
} else {
r = float64(s) <= cv
}
default:
return ValidatorErrorf("invalid type %T", s)
}
if !r {
return ValidatorResult(false, "greater or equal to %v", s)
}
return ValidatorResult(true, "less than %v", s)
case "match", "~=":
if len(args) != 1 {
return ValidatorErrorf("match requires a regexp argument")
}
s, ok := args[0].Value().(string)
if !ok {
return ValidatorErrorf("match requires a regexp argument")
}
re, err := regexp.Compile(s)
if err != nil {
return ValidatorErrorf("regexp %s: %s", s, err)
}
s, ok = value.(string)
if !ok {
return ValidatorErrorf("no string to match regexp")
}
if !re.MatchString(s) {
return ValidatorResult(false, "invalid value %q", s)
}
return ValidatorResult(true, "valid value %q", s)
case "type":
e := ExpressionType(value)
for _, t := range args {
s, err := StringValue("type arg", t.Value())
if err != nil {
return ValidatorErrorf("%s: %s", op, err)
}
if s == e {
return ValidatorResult(true, "is of type %s", s)
}
if reason != "(" {
reason += " and "
}
reason += fmt.Sprintf("is not of type %s", s)
}
if len(args) == 1 {
return ValidatorResult(false, reason[1:])
}
return ValidatorResult(false, reason+")")
case "dnsname":
s, err := StringValue(op, value)
if err != nil {
return ValidatorErrorf("%s: %s", op, err)
}
if r := IsWildcardDNS1123Subdomain(s); r != nil {
if r := IsDNS1123Subdomain(s); r != nil {
return ValidatorResult(false, "is no dns name: %s", r)
}
}
return ValidatorResult(true, "is dns name")
case "dnslabel":
s, err := StringValue(op, value)
if err != nil {
return ValidatorErrorf("%s: %s", op, err)
}
r := IsDNS1123Label(s)
return SimpleValidatorResult(r == nil, "is dns label", "is no dns label: %s", r)
case "dnsdomain":
s, err := StringValue(op, value)
if err != nil {
return ValidatorErrorf("%s: %s", op, err)
}
r := IsDNS1123Subdomain(s)
return SimpleValidatorResult(r == nil, "is dns domain", "is no dns domain: %s", r)
case "wildcarddnsdomain":
s, err := StringValue(op, value)
if err != nil {
return ValidatorErrorf("%s: %s", op, err)
}
r := IsWildcardDNS1123Subdomain(s)
return SimpleValidatorResult(r == nil, "is wildcard dns domain", "is no wildcard dns domain: %s", r)
case "ip":
s, err := StringValue(op, value)
if err != nil {
return ValidatorErrorf("%s: %s", op, err)
}
ip := net.ParseIP(s)
return SimpleValidatorResult(ip != nil, "is ip address", "is no ip address: %s", s)
case "cidr":
s, err := StringValue(op, value)
if err != nil {
return ValidatorErrorf("%s: %s", op, err)
}
_, _, err = net.ParseCIDR(s)
return SimpleValidatorResult(err == nil, "is CIDR", "is no CIDR: %s", err)
default:
v := validators[op]
if v != nil {
vargs := []interface{}{}
for _, a := range args {
vargs = append(vargs, a.Value())
}
return v(value, binding, vargs...)
}
return ValidatorErrorf("unknown validation operator %q", op)
}
}
func StringValue(msg string, v interface{}) (string, error) {
s, ok := v.(string)
if !ok {
return "", fmt.Errorf("%s requires string, but got %s", msg, ExpressionType(v))
}
return s, nil
}
func ValidatorErrorf(msgfmt string, args ...interface{}) (bool, string, error, bool) {
return false, "", fmt.Errorf(msgfmt, args...), true
}
func ValidatorResult(r bool, msgfmt string, args ...interface{}) (bool, string, error, bool) {
return r, fmt.Sprintf(msgfmt, args...), nil, true
}
func SimpleValidatorResult(r bool, t, f string, args ...interface{}) (bool, string, error, bool) {
if r {
return ValidatorResult(r, t)
}
return ValidatorResult(r, fmt.Sprintf(f, args...))
}