-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.go
More file actions
810 lines (755 loc) · 22.2 KB
/
Copy pathvalidate.go
File metadata and controls
810 lines (755 loc) · 22.2 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
package dyfields
import (
"crypto/rand"
"encoding/hex"
"fmt"
"regexp"
"sort"
"strings"
)
// VisibleSet is the outcome of evaluating every visibility condition against a
// document. Field keys are index paths (`sinks[0].partition_key`) so a caller
// can address one row of a table, the same way error paths do.
type VisibleSet struct {
Groups map[string]bool `json:"groups"`
Fields map[string]bool `json:"fields"`
}
// evalCtx is one scope bound to one set of values: the root document, or one
// item of an object_list.
type evalCtx struct {
parent *evalCtx
scope *cscope
values map[string]any
sprefix string // secrets key prefix, "" or ending in "."
path string // error path prefix, "" or ending in "."
ipath string // $id path prefix, "" or ending in "."
}
type validator struct {
c *Compiled
doc ValueDocument
errs FieldErrors
groupVisible map[string]bool
groupActive map[string]bool
visible map[string]bool
seenSecrets map[string]bool
transient []func()
collectOnly bool
// serverSide drops the verdicts only a transient value could answer. Apply
// sets it; see Compiled.Apply.
serverSide bool
}
// Validate checks a complete document against the schema and returns the
// normalized document: invisible values removed, defaults applied, generated
// $ids filled in, transient values dropped.
//
// It does NOT check readonly. That needs a baseline to compare against, which
// only Apply has. Do not treat a successful Validate as proof that a readonly
// field was not tampered with.
func (c *Compiled) Validate(doc ValueDocument) (ValueDocument, FieldErrors) {
return c.validateDoc(doc, false)
}
func (c *Compiled) validateDoc(doc ValueDocument, serverSide bool) (ValueDocument, FieldErrors) {
v := c.newValidator(doc)
v.serverSide = serverSide
v.run()
if len(v.errs) == 0 {
// Transient values exist only for the duration of validation; on
// failure they stay, because the caller may hand them back to the form.
for _, drop := range v.transient {
drop()
}
}
sort.SliceStable(v.errs, func(i, j int) bool { return v.errs[i].Path < v.errs[j].Path })
return v.doc, v.errs
}
// Visible reports which groups and fields are shown for the given values. A
// renderer calls this to decide what to draw without re-implementing the rules.
func (c *Compiled) Visible(doc ValueDocument) VisibleSet {
v := c.newValidator(doc)
v.collectOnly = true
v.run()
return VisibleSet{Groups: v.groupVisible, Fields: v.visible}
}
func (c *Compiled) newValidator(doc ValueDocument) *validator {
d := doc.Clone()
if d.Values == nil {
d.Values = map[string]any{}
}
if d.Secrets == nil {
d.Secrets = map[string]string{}
}
return &validator{
c: c,
doc: d,
groupVisible: map[string]bool{},
groupActive: map[string]bool{},
visible: map[string]bool{},
seenSecrets: map[string]bool{},
}
}
func (v *validator) run() {
root := &evalCtx{scope: v.c.root, values: v.doc.Values}
v.settle(root)
v.checkScope(root)
v.checkStraySecrets()
}
func (v *validator) add(e FieldError) {
if !v.collectOnly {
v.errs = append(v.errs, e)
}
}
// ---- visibility -----------------------------------------------------------
// settle runs steps 1-4 of the validation contract: compute visibility, apply
// defaults to what is visible, and repeat until nothing changes.
//
// Removal waits for the fixed point. Clearing as we go would be destructive in
// the middle of a computation that is not finished yet: a field whose default
// has not been applied on the first pass reads as absent, everything gated on
// it looks invisible, and its values would be gone before the next pass could
// discover they belong. Defaults are only additive, so they can safely happen
// inside the loop; deletion happens once, at the end.
//
// The loop terminates because same-scope visible_when is acyclic (checked at
// compile time) and each field can flip visibility or gain a default at most
// once per level of the dependency chain.
func (v *validator) settle(ctx *evalCtx) {
limit := len(ctx.scope.fields) + 2
for i := 0; i < limit; i++ {
if ctx.scope == v.c.root {
v.computeGroups(ctx)
}
changed := false
for _, cf := range ctx.scope.fields {
key := ctx.path + cf.f.Name
vis := v.fieldVisible(ctx, cf)
if old, seen := v.visible[key]; !seen || old != vis {
v.visible[key] = vis
changed = true
}
if vis && v.applyDefault(ctx, cf) {
changed = true
}
}
if !changed {
break
}
}
for _, cf := range ctx.scope.fields {
if !v.visible[ctx.path+cf.f.Name] {
v.clear(ctx, cf)
}
}
}
func (v *validator) computeGroups(ctx *evalCtx) {
for _, g := range v.c.groups {
vis := g.g.VisibleWhen == nil || v.eval(ctx, g.g.VisibleWhen)
v.groupVisible[g.g.Key] = vis
active := true
if g.g.Mode == ModeToggleable && g.toggle != nil {
b, _ := toBool(ctx.values[g.toggle.f.Name])
active = b
}
v.groupActive[g.g.Key] = vis && active
}
}
func (v *validator) fieldVisible(ctx *evalCtx, cf *cfield) bool {
if ctx.scope == v.c.root && cf.group != "" {
if !v.groupVisible[cf.group] {
return false
}
// The toggle survives its own group being switched off; that is the
// whole point of it, and it is what the next open reads back.
if !cf.isToggle && !v.groupActive[cf.group] {
return false
}
}
if cf.f.VisibleWhen != nil && !v.eval(ctx, cf.f.VisibleWhen) {
return false
}
return true
}
// clear removes an invisible field's value, including every secret underneath
// it. Invisible means absent: keeping a residue would leave a document whose
// behaviour cannot be read off its own values.
func (v *validator) clear(ctx *evalCtx, cf *cfield) bool {
changed := false
if _, ok := ctx.values[cf.f.Name]; ok {
delete(ctx.values, cf.f.Name)
changed = true
}
if cf.f.Type == TypeSecret {
key := ctx.sprefix + cf.f.Name
if _, ok := v.doc.Secrets[key]; ok {
delete(v.doc.Secrets, key)
changed = true
}
return changed
}
if cf.child != nil {
// The flat secrets container turns "clear the whole subtree" into a
// prefix scan, instead of a second tree walk that has to stay in sync.
prefix := ctx.sprefix + cf.f.Name + "."
for k := range v.doc.Secrets {
if strings.HasPrefix(k, prefix) {
delete(v.doc.Secrets, k)
changed = true
}
}
}
return changed
}
func (v *validator) applyDefault(ctx *evalCtx, cf *cfield) bool {
if cf.f.Default == nil || cf.f.Type == TypeSecret {
return false
}
if cur, ok := ctx.values[cf.f.Name]; ok && cur != nil {
return false
}
ctx.values[cf.f.Name] = cloneValue(cf.f.Default)
return true
}
// ---- condition evaluation -------------------------------------------------
func (v *validator) eval(ctx *evalCtx, c *Condition) bool {
if c == nil {
return true
}
if len(c.AllOf) > 0 {
for _, sub := range c.AllOf {
if !v.eval(ctx, sub) {
return false
}
}
return true
}
if len(c.AnyOf) > 0 {
for _, sub := range c.AnyOf {
if v.eval(ctx, sub) {
return true
}
}
return false
}
if c.Not != nil {
return !v.eval(ctx, c.Not)
}
val, cf := v.lookup(ctx, parseRef(c.Field))
switch {
case c.hasEquals:
return equalValues(val, c.Equals)
case c.In != nil:
return containsValue(c.In, val)
case c.NotIn != nil:
return !containsValue(c.NotIn, val)
case c.IsTrue != nil:
b, _ := toBool(val)
return b == *c.IsTrue
case c.IsEmpty != nil:
return isEmptyValue(val) == *c.IsEmpty
case c.EqualsField != "":
other, _ := v.lookup(ctx, parseRef(c.EqualsField))
return equalValues(val, other)
case c.NotEqualsField != "":
other, _ := v.lookup(ctx, parseRef(c.NotEqualsField))
return !equalValues(val, other)
}
var target string
var want func(int) bool
switch {
case c.GtField != "":
target, want = c.GtField, func(r int) bool { return r > 0 }
case c.GteField != "":
target, want = c.GteField, func(r int) bool { return r >= 0 }
case c.LtField != "":
target, want = c.LtField, func(r int) bool { return r < 0 }
case c.LteField != "":
target, want = c.LteField, func(r int) bool { return r <= 0 }
default:
return true
}
other, _ := v.lookup(ctx, parseRef(target))
t := TypeString
format := ""
if cf != nil {
t, format = cf.f.Type, cf.f.Format
}
cmp, ok := compareOrdered(val, other, t, format)
if !ok {
// A comparison against a missing value is not an error here: the field
// simply is not in the state the condition describes.
return false
}
return want(cmp)
}
func containsValue(list []any, v any) bool {
for _, e := range list {
if equalValues(e, v) {
return true
}
}
return false
}
// lookup resolves a reference outwards through the scope chain.
func (v *validator) lookup(ctx *evalCtx, r ref) (any, *cfield) {
target := ctx
if r.root {
for target.parent != nil {
target = target.parent
}
} else {
for i := 0; i < r.up; i++ {
if target.parent == nil {
return nil, nil
}
target = target.parent
}
}
cf := target.scope.byName[r.name]
if cf == nil {
return nil, nil
}
if vis, known := v.visible[target.path+r.name]; known && !vis {
// Invisible means absent. Saying so here keeps the answer the same
// before and after the values are physically removed.
return nil, cf
}
if cf.f.Type == TypeSecret {
if s, ok := v.doc.Secrets[target.sprefix+r.name]; ok {
return s, cf
}
return nil, cf
}
return target.values[r.name], cf
}
// ---- value checking -------------------------------------------------------
func (v *validator) checkScope(ctx *evalCtx) {
for _, cf := range ctx.scope.fields {
if !v.visible[ctx.path+cf.f.Name] {
continue
}
// A transient field is checked either way, because the side effects
// matter: the value still has to be dropped from the output and the
// secret still has to be marked seen. What Apply throws away is the
// verdict, not the visit.
n := len(v.errs)
v.checkField(ctx, cf)
if v.serverSide && cf.f.Transient {
v.errs = v.errs[:n]
}
}
// valid_when is cross-field, so it runs only after every field has been
// checked on its own.
for _, cf := range ctx.scope.fields {
if !v.visible[ctx.path+cf.f.Name] {
continue
}
for _, r := range cf.f.ValidWhen {
if v.serverSide && v.c.clientOnly[r] {
continue
}
v.checkRule(ctx, r, ctx.path+cf.f.Name, cf.f.Name, cf.group)
}
}
if ctx.scope == v.c.root {
for _, g := range v.c.groups {
if !v.groupActive[g.g.Key] {
continue
}
for _, r := range g.g.ValidWhen {
if v.serverSide && v.c.clientOnly[r] {
continue
}
v.checkRule(ctx, r, g.g.Key, "", g.g.Key)
}
}
}
v.checkUnknownKeys(ctx)
}
func (v *validator) checkRule(ctx *evalCtx, r *Rule, path, field, group string) {
if r == nil || r.When == nil || v.eval(ctx, r.When) {
return
}
code := r.Code
if code == "" {
code = ErrInvalid
}
reason := r.Reason
if reason == "" {
reason = "the value does not satisfy this rule"
}
v.add(FieldError{Path: path, Field: field, Group: group, ItemPath: strings.TrimSuffix(ctx.ipath, "."),
Code: code, Reason: reason})
}
// checkUnknownKeys rejects keys the schema does not declare. Silently ignoring
// them makes a misspelled setting look like it took effect.
func (v *validator) checkUnknownKeys(ctx *evalCtx) {
keys := make([]string, 0, len(ctx.values))
for k := range ctx.values {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
if k == KeyItemID || k == KeyDeleted {
continue
}
cf, ok := ctx.scope.byName[k]
if !ok {
v.add(FieldError{Path: ctx.path + k, Field: k, ItemPath: strings.TrimSuffix(ctx.ipath, "."),
Code: ErrUnknownField, Reason: fmt.Sprintf("field %q is not declared in the schema", k)})
continue
}
if cf.f.Type == TypeSecret {
v.add(FieldError{Path: ctx.path + k, Field: k, Group: cf.group,
ItemPath: strings.TrimSuffix(ctx.ipath, "."), Code: ErrType,
Reason: "a secret must be sent in the secrets container, not in values"})
}
}
}
// checkStraySecrets reports secrets that no declared field claims. Anything
// left over is either a typo or a value that will never be read.
func (v *validator) checkStraySecrets() {
keys := make([]string, 0, len(v.doc.Secrets))
for k := range v.doc.Secrets {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
if !v.seenSecrets[k] {
v.add(FieldError{Path: k, Code: ErrUnknownField,
Reason: fmt.Sprintf("secret %q does not match any visible secret field", k)})
}
}
}
func (v *validator) checkField(ctx *evalCtx, cf *cfield) {
f := cf.f
path := ctx.path + f.Name
ipath := strings.TrimSuffix(ctx.ipath, ".")
fail := func(code, format string, args ...any) {
v.add(FieldError{Path: path, Field: f.Name, Group: cf.group, ItemPath: ipath,
Code: code, Reason: fmt.Sprintf(format, args...)})
}
required := f.Required || (f.RequiredWhen != nil && v.eval(ctx, f.RequiredWhen))
if f.Type == TypeSecret {
key := ctx.sprefix + f.Name
v.seenSecrets[key] = true
s, ok := v.doc.Secrets[key]
if !ok || s == "" {
if required {
fail(ErrRequired, "%s is required", label(f))
}
return
}
v.checkString(s, f.Format, f.Pattern, cf.pattern, f.MinLength, f.MaxLength, fail)
if f.Transient {
v.transient = append(v.transient, func() { delete(v.doc.Secrets, key) })
}
return
}
raw, present := ctx.values[f.Name]
if f.Type.IsContainer() {
v.checkContainer(ctx, cf, raw, present, path, fail)
return
}
if !present || isEmptyValue(raw) {
if required {
fail(ErrRequired, "%s is required", label(f))
}
return
}
if f.Transient {
name := f.Name
vals := ctx.values
v.transient = append(v.transient, func() { delete(vals, name) })
}
switch f.Type {
case TypeJSON:
// The escape hatch: any JSON value passes, and validation stops at its
// boundary. Checking inside it would make the hatch useless.
return
case TypeEnum:
v.checkEnum(f, raw, fail)
return
}
if reason, ok := checkScalarType(raw, f.Type); !ok {
fail(ErrType, "%s", reason)
return
}
switch f.Type {
case TypeString, TypeFile:
s, _ := toString(raw)
v.checkString(s, f.Format, f.Pattern, cf.pattern, f.MinLength, f.MaxLength, fail)
case TypeDatetime:
if reason, ok := checkDatetime(raw, f.Format); !ok {
fail(ErrFormat, "%s", reason)
}
case TypeInteger, TypeNumber, TypeDecimal:
v.checkNumberRange(raw, f.Min, f.Max, fail)
}
}
func label(f *Field) string {
if f.Label != "" {
return f.Label
}
return f.Name
}
func (v *validator) checkString(s, format, pattern string, re *regexp.Regexp,
minLen, maxLen *int, fail func(string, string, ...any)) {
if minLen != nil && len([]rune(s)) < *minLen {
fail(ErrLength, "must be at least %d %s", *minLen, plural(*minLen, "character", "characters"))
}
if maxLen != nil && len([]rune(s)) > *maxLen {
fail(ErrLength, "must be at most %d %s", *maxLen, plural(*maxLen, "character", "characters"))
}
if format != "" {
if reason, ok := checkFormat(s, format); !ok {
fail(ErrFormat, "%s", reason)
}
}
if re != nil && !re.MatchString(s) {
fail(ErrPattern, "must match %s", pattern)
}
}
func (v *validator) checkNumberRange(raw any, min, max *float64, fail func(string, string, ...any)) {
n, ok := toFloat(raw)
if !ok {
return
}
if min != nil && n < *min {
fail(ErrRange, "must be at least %v", *min)
}
if max != nil && n > *max {
fail(ErrRange, "must be at most %v", *max)
}
}
func (v *validator) checkEnum(f *Field, raw any, fail func(string, string, ...any)) {
inOptions := func(x any) bool {
for _, o := range f.Options {
if equalValues(o.Value, x) {
return true
}
}
return false
}
if !f.Multiple {
if !inOptions(raw) {
fail(ErrEnum, "%v is not one of the allowed options", raw)
}
return
}
arr, ok := raw.([]any)
if !ok {
fail(ErrType, "must be an array of options")
return
}
seen := map[string]bool{}
for _, e := range arr {
if !inOptions(e) {
fail(ErrEnum, "%v is not one of the allowed options", e)
}
k := normalizeForUnique(e, "")
if seen[k] {
fail(ErrDuplicate, "%v is selected twice", e)
}
seen[k] = true
}
}
// checkContainer validates list, map and object_list. Containers never use
// required: min_items says the same thing, and one mechanism per meaning is
// what keeps callers from guessing which one wins.
func (v *validator) checkContainer(ctx *evalCtx, cf *cfield, raw any, present bool,
path string, fail func(string, string, ...any)) {
f := cf.f
count := 0
switch f.Type {
case TypeList:
if present {
arr, ok := raw.([]any)
if !ok {
fail(ErrType, "must be an array")
return
}
count = len(arr)
for i, e := range arr {
v.checkItemValue(ctx, cf, e, fmt.Sprintf("%s[%d]", path, i), "")
}
}
case TypeMap:
if present {
m, ok := raw.(map[string]any)
if !ok {
fail(ErrType, "must be an object")
return
}
count = len(m)
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
if cf.keyPattern != nil && !cf.keyPattern.MatchString(k) {
v.add(FieldError{Path: path, Field: f.Name, Group: cf.group, Key: k,
ItemPath: strings.TrimSuffix(ctx.ipath, "."), Code: ErrKeyPattern,
Reason: fmt.Sprintf("key %q must match %s", k, f.KeyPattern)})
}
v.checkItemValue(ctx, cf, m[k], path+"."+k, k)
}
}
case TypeObjectList:
count = v.checkObjectList(ctx, cf, raw, present, path, fail)
}
if f.MinItems != nil && count < *f.MinItems {
fail(ErrMinItems, "needs at least %d %s", *f.MinItems, plural(*f.MinItems, "entry", "entries"))
}
if f.MaxItems != nil && count > *f.MaxItems {
fail(ErrMaxItems, "allows at most %d %s", *f.MaxItems, plural(*f.MaxItems, "entry", "entries"))
}
}
// checkItemValue validates one element of a list or map against Items.
func (v *validator) checkItemValue(ctx *evalCtx, cf *cfield, e any, path, key string) {
it := cf.f.Items
if it == nil {
return
}
fail := func(code, format string, args ...any) {
v.add(FieldError{Path: path, Field: cf.f.Name, Group: cf.group, Key: key,
ItemPath: strings.TrimSuffix(ctx.ipath, "."), Code: code,
Reason: fmt.Sprintf(format, args...)})
}
if it.Type == TypeEnum {
v.checkEnum(&Field{Type: TypeEnum, Options: it.Options}, e, fail)
return
}
if reason, ok := checkScalarType(e, it.Type); !ok {
fail(ErrType, "%s", reason)
return
}
switch it.Type {
case TypeString, TypeFile, TypeSecret:
s, _ := toString(e)
v.checkString(s, it.Format, it.Pattern, cf.itemPattern, it.MinLength, it.MaxLength, fail)
case TypeDatetime:
if reason, ok := checkDatetime(e, it.Format); !ok {
fail(ErrFormat, "%s", reason)
}
case TypeInteger, TypeNumber, TypeDecimal:
v.checkNumberRange(e, it.Min, it.Max, fail)
}
}
// checkObjectList validates every item in its own scope, then the constraints
// that belong to the list as a whole. Items never see each other: the only
// cross-item rules are unique and min/max items.
func (v *validator) checkObjectList(ctx *evalCtx, cf *cfield, raw any, present bool,
path string, fail func(string, string, ...any)) int {
if !present {
return 0
}
arr, ok := raw.([]any)
if !ok {
fail(ErrType, "must be an array")
return 0
}
f := cf.f
kept := make([]any, 0, len(arr))
seenID := map[string]bool{}
type entryRef struct{ path, ipath string }
uniq := map[string][]entryRef{}
for i, e := range arr {
itemPath := fmt.Sprintf("%s[%d]", path, i)
item, ok := e.(map[string]any)
if !ok {
v.add(FieldError{Path: itemPath, Field: f.Name, Group: cf.group, Code: ErrType,
Reason: "each entry must be an object"})
continue
}
if b, _ := toBool(item[KeyDeleted]); b {
// A tombstone is an instruction for Apply; a complete document has
// no business carrying one, so it is simply dropped here.
continue
}
id, hasID := "", false
if s, ok := item[KeyItemID].(string); ok && s != "" {
id, hasID = s, true
}
switch {
case hasID && !itemIDRe.MatchString(id):
v.add(FieldError{Path: itemPath, Field: f.Name, Group: cf.group, Code: ErrBadItemID,
Reason: fmt.Sprintf("$id %q must match [A-Za-z0-9_-]{1,64}", id)})
case hasID && seenID[id]:
v.add(FieldError{Path: itemPath, Field: f.Name, Group: cf.group, Code: ErrDuplicate,
Reason: fmt.Sprintf("$id %q is used by more than one entry", id)})
case !hasID && cf.requiresItemID:
// The secrets key is built from the $id, so the client has to pick
// it before it can even write the secret. Filling it in here would
// be too late.
v.add(FieldError{Path: itemPath, Field: f.Name, Group: cf.group, Code: ErrMissingItemID,
Reason: "this entry holds a secret, so it must carry a client-generated $id"})
id = newItemID()
case !hasID:
id = newItemID()
item[KeyItemID] = id
}
if id != "" {
seenID[id] = true
}
sub := &evalCtx{
parent: ctx,
scope: cf.child,
values: item,
sprefix: ctx.sprefix + f.Name + "." + id + ".",
path: itemPath + ".",
ipath: ctx.ipath + f.Name + "." + id + ".",
}
v.settle(sub)
v.checkScope(sub)
if len(f.Unique) > 0 {
key := v.uniqueKey(sub, cf, f.Unique)
uniq[key] = append(uniq[key], entryRef{itemPath, strings.TrimSuffix(sub.ipath, ".")})
}
kept = append(kept, item)
}
for _, paths := range uniq {
if len(paths) < 2 {
continue
}
for _, p := range paths[1:] {
// Deliberately no value in the message: unique may cover a secret
// field, and the default "the value X is duplicated" would leak it.
v.add(FieldError{Path: p.path, ItemPath: p.ipath, Field: f.Name, Group: cf.group, Code: ErrDuplicate,
Reason: fmt.Sprintf("another entry already uses the same %s",
strings.Join(f.Unique, " + "))})
}
}
ctx.values[f.Name] = kept
return len(kept)
}
// uniqueKey builds the comparison key for one item. Invisible fields have no
// value by this point, so they compare as empty, which is what they are.
func (v *validator) uniqueKey(sub *evalCtx, cf *cfield, names []string) string {
parts := make([]string, 0, len(names))
for _, n := range names {
target := cf.child.byName[n]
if target == nil {
parts = append(parts, "")
continue
}
var val any
if target.f.Type == TypeSecret {
if s, ok := v.doc.Secrets[sub.sprefix+n]; ok {
val = s
}
} else {
val = sub.values[n]
}
parts = append(parts, normalizeForUnique(val, target.f.Format))
}
return strings.Join(parts, "\x00")
}
// newItemID generates an $id for an entry that does not need a client-chosen
// one. It only has to be unique inside its own list.
func newItemID() string {
var b [8]byte
if _, err := rand.Read(b[:]); err != nil {
return "i0"
}
return "i" + hex.EncodeToString(b[:])
}