-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapply.go
More file actions
408 lines (380 loc) · 12.1 KB
/
Copy pathapply.go
File metadata and controls
408 lines (380 loc) · 12.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
package dyfields
import (
"encoding/json"
"fmt"
"sort"
"strings"
)
// Patch is a partial update. It is a separate type from ValueDocument because
// a patch has to say three different things about a secret — leave it alone,
// set it, clear it — and a plain map[string]string can only say two. The
// pointer makes "clear" (JSON null) distinct from "unchanged" (empty string).
type Patch struct {
Values map[string]any `json:"values"`
Secrets map[string]*string `json:"secrets,omitempty"`
}
// ParsePatch reads a patch document.
func ParsePatch(data []byte) (Patch, error) {
var p Patch
if err := json.Unmarshal(data, &p); err != nil {
return Patch{}, fmt.Errorf("dyfields: parse patch: %w", err)
}
p.Values, _ = normalizeJSONValue(p.Values).(map[string]any)
return p, nil
}
// Apply merges a patch into an existing document and validates the result.
//
// The merge is a patch, not a replace: a key that is absent keeps its current
// value. This matters most for object_list, where entries are aligned by $id
// and an absent entry is retained — the alternative, "absent means delete",
// turns the most natural front-end pattern (send only what changed) into
// silent data loss.
//
// Apply is also the only place readonly is enforced, because rejecting a
// *change* needs something to compare against.
//
// It reports nothing about a transient field, nor about a valid_when rule that
// reads one. A transient value is dropped from Validate's output, so it is
// never in a payload, never in a patch, and never in the document being merged
// into: a required transient field would read as missing on every single
// update, and "confirm your password" would fail against a document that
// structurally cannot hold a confirmation. Those questions have exactly one
// place they can be answered, which is the form that holds the value -- a
// server cannot check what it was never sent, the mirror image of the rule
// that keeps a client from checking what it was never shown.
func (c *Compiled) Apply(current ValueDocument, patch Patch) (ValueDocument, FieldErrors) {
base := current.Clone()
if base.Values == nil {
base.Values = map[string]any{}
}
if base.Secrets == nil {
base.Secrets = map[string]string{}
}
merged := base.Clone()
mergeScope(c.root, merged.Values, patch.Values, "", merged.Secrets)
applySecrets(merged.Secrets, patch.Secrets)
errs := c.checkReadOnly(base, merged)
out, verrs := c.validateDoc(merged, true)
errs = append(errs, verrs...)
sort.SliceStable(errs, func(i, j int) bool { return errs[i].Path < errs[j].Path })
return out, errs
}
// ImpactOf reports which paths hold a value now but would not after the patch.
// Changing one select box can invalidate a whole subtree, and the caller needs
// to be able to warn about that before the values are gone, not after.
func (c *Compiled) ImpactOf(current ValueDocument, patch Patch) []string {
before, _ := c.Validate(current)
after, _ := c.Apply(current, patch)
have := map[string]bool{}
collectPaths(c.root, after.Values, "", have)
for k := range after.Secrets {
have[k] = true
}
var lost []string
old := map[string]bool{}
collectPaths(c.root, before.Values, "", old)
for k := range before.Secrets {
old[k] = true
}
for p := range old {
if !have[p] {
lost = append(lost, p)
}
}
sort.Strings(lost)
return lost
}
// Redact produces a version safe to hand out or log: the secret values are
// replaced by the list of paths that have one set, and any field declaring a
// mask is rewritten according to it.
//
// The two mechanisms answer different questions. A secret is kept out of the
// value tree entirely, so it cannot be logged by accident; a mask is for a
// value the application genuinely needs to store and read back -- a national
// ID, a phone number -- that still has no business appearing in an audit
// record in full.
//
// Redact never changes the document you persist. Validate and Apply are
// untouched by masks.
func (c *Compiled) Redact(doc ValueDocument) PublicDocument {
out := PublicDocument{Values: cloneMap(doc.Values)}
maskScope(c.root, out.Values)
for k := range doc.Secrets {
out.SecretsSet = append(out.SecretsSet, k)
}
sort.Strings(out.SecretsSet)
return out
}
// maskScope rewrites the masked fields of one scope in place, descending into
// object_list entries so a mask declared on a nested field still fires. It
// walks the schema rather than the values, so a key the schema does not
// declare is left exactly as it was -- Validate is what reports those, and
// silently rewriting them here would hide the typo.
func maskScope(sc *cscope, values map[string]any) {
for _, cf := range sc.fields {
raw, ok := values[cf.f.Name]
if !ok || raw == nil {
continue
}
if cf.child != nil {
arr, _ := raw.([]any)
for _, e := range arr {
if item, ok := e.(map[string]any); ok {
maskScope(cf.child, item)
}
}
continue
}
switch {
case cf.f.Mask == nil:
case cf.f.Mask.Omit:
delete(values, cf.f.Name)
default:
values[cf.f.Name] = cf.f.Mask.Apply(raw)
}
}
}
// ---- merging --------------------------------------------------------------
func mergeScope(sc *cscope, cur, patch map[string]any, sprefix string, secrets map[string]string) {
keys := make([]string, 0, len(patch))
for k := range patch {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
pv := patch[k]
cf := sc.byName[k]
if cf == nil {
// Unknown keys are carried through so that Validate reports them.
// Dropping them here would make a typo look accepted.
if pv == nil {
delete(cur, k)
} else {
cur[k] = cloneValue(pv)
}
continue
}
if pv == nil {
delete(cur, k)
dropSecrets(secrets, sprefix+k)
continue
}
if cf.f.Type == TypeObjectList {
cur[k] = mergeObjectList(cf, cur[k], pv, sprefix+k+".", secrets)
continue
}
// list and map are replaced wholesale. Element-level merging would
// need its own patch grammar (insert where? delete which key?), and
// that is a separate specification, not a corner of this one.
cur[k] = cloneValue(pv)
}
}
func mergeObjectList(cf *cfield, curRaw, patchRaw any, prefix string, secrets map[string]string) any {
patchArr, ok := patchRaw.([]any)
if !ok {
return cloneValue(patchRaw)
}
curArr, _ := curRaw.([]any)
order := make([]string, 0, len(curArr))
byID := map[string]map[string]any{}
var loose []any
for _, e := range curArr {
item, ok := e.(map[string]any)
if !ok {
loose = append(loose, e)
continue
}
id, _ := item[KeyItemID].(string)
if id == "" {
loose = append(loose, item)
continue
}
if _, dup := byID[id]; !dup {
order = append(order, id)
}
byID[id] = item
}
for _, e := range patchArr {
p, ok := e.(map[string]any)
if !ok {
loose = append(loose, e)
continue
}
id, _ := p[KeyItemID].(string)
if del, _ := toBool(p[KeyDeleted]); del {
if id == "" {
continue
}
delete(byID, id)
for i, o := range order {
if o == id {
order = append(order[:i], order[i+1:]...)
break
}
}
dropSecrets(secrets, prefix+id)
continue
}
if id == "" {
// A new entry with no $id: keep it as sent. If the entry holds a
// secret, Validate rejects it, because only the client could have
// picked the id the secret key was written with.
loose = append(loose, cloneValue(p))
continue
}
exist, found := byID[id]
if !found {
item := map[string]any{}
mergeScope(cf.child, item, p, prefix+id+".", secrets)
item[KeyItemID] = id
byID[id] = item
order = append(order, id)
continue
}
mergeScope(cf.child, exist, p, prefix+id+".", secrets)
}
out := make([]any, 0, len(order)+len(loose))
for _, id := range order {
out = append(out, byID[id])
}
out = append(out, loose...)
return out
}
// applySecrets follows the three-way rule: absent keeps, empty string keeps,
// null clears, anything else sets. Empty string has to mean "unchanged"
// because a secret is never read back — the form shows a placeholder, and the
// user who does not touch it submits exactly that empty string.
func applySecrets(cur map[string]string, patch map[string]*string) {
for k, v := range patch {
switch {
case v == nil:
delete(cur, k)
case *v == "":
// keep
default:
cur[k] = *v
}
}
}
// dropSecrets removes the secret at a path and everything below it.
func dropSecrets(secrets map[string]string, path string) {
delete(secrets, path)
prefix := path + "."
for k := range secrets {
if strings.HasPrefix(k, prefix) {
delete(secrets, k)
}
}
}
// ---- readonly -------------------------------------------------------------
// checkReadOnly compares the merged document against the baseline. Only a
// change is rejected; a readonly field that is resubmitted unchanged is fine,
// because that is what a form round-trip looks like.
func (c *Compiled) checkReadOnly(base, merged ValueDocument) FieldErrors {
v := c.newValidator(merged)
v.collectOnly = true
v.run()
var errs FieldErrors
var walk func(parent *evalCtx, sc *cscope, oldVals, newVals map[string]any, sprefix, path, ipath string)
walk = func(parent *evalCtx, sc *cscope, oldVals, newVals map[string]any, sprefix, path, ipath string) {
// The parent link matters: a readonly_when inside an entry may read
// `^.` from the entry's own list, and without the chain it would
// resolve to nothing and silently never lock anything.
ctx := &evalCtx{parent: parent, scope: sc, values: newVals,
sprefix: sprefix, path: path, ipath: ipath}
for _, cf := range sc.fields {
ro := cf.f.ReadOnly
if !ro && cf.f.ReadOnlyWhen != nil {
ro = v.evalAgainst(merged, ctx, cf.f.ReadOnlyWhen)
}
if ro {
var before, after any
if cf.f.Type == TypeSecret {
before, after = base.Secrets[sprefix+cf.f.Name], merged.Secrets[sprefix+cf.f.Name]
} else {
before, after = oldVals[cf.f.Name], newVals[cf.f.Name]
}
if !sameJSON(before, after) {
errs = append(errs, FieldError{Path: path + cf.f.Name, Field: cf.f.Name,
Group: cf.group, ItemPath: strings.TrimSuffix(ipath, "."), Code: ErrReadOnly,
Reason: fmt.Sprintf("%s is read-only and cannot be changed", label(cf.f))})
}
}
if cf.child == nil {
continue
}
oldItems := itemsByID(oldVals[cf.f.Name])
newArr, _ := newVals[cf.f.Name].([]any)
for i, e := range newArr {
item, ok := e.(map[string]any)
if !ok {
continue
}
id, _ := item[KeyItemID].(string)
prev := oldItems[id]
if prev == nil {
// A brand-new entry has nothing to be read-only against.
continue
}
walk(ctx, cf.child, prev, item,
sprefix+cf.f.Name+"."+id+".",
fmt.Sprintf("%s%s[%d].", path, cf.f.Name, i),
ipath+cf.f.Name+"."+id+".")
}
}
}
walk(nil, c.root, base.Values, merged.Values, "", "", "")
return errs
}
// evalAgainst evaluates a condition against a document other than the one the
// validator was built for, which is what the readonly walk needs.
func (v *validator) evalAgainst(doc ValueDocument, ctx *evalCtx, c *Condition) bool {
saved := v.doc
v.doc = doc
defer func() { v.doc = saved }()
return v.eval(ctx, c)
}
func itemsByID(raw any) map[string]map[string]any {
out := map[string]map[string]any{}
arr, _ := raw.([]any)
for _, e := range arr {
if item, ok := e.(map[string]any); ok {
if id, _ := item[KeyItemID].(string); id != "" {
out[id] = item
}
}
}
return out
}
func sameJSON(a, b any) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
ja, err1 := json.Marshal(a)
jb, err2 := json.Marshal(b)
return err1 == nil && err2 == nil && string(ja) == string(jb)
}
// collectPaths lists every path that currently holds a value, using $id for
// object_list entries so the paths stay comparable across an edit.
func collectPaths(sc *cscope, values map[string]any, prefix string, out map[string]bool) {
for _, cf := range sc.fields {
raw, ok := values[cf.f.Name]
if !ok || raw == nil {
continue
}
path := prefix + cf.f.Name
out[path] = true
if cf.child == nil {
continue
}
arr, _ := raw.([]any)
for _, e := range arr {
item, ok := e.(map[string]any)
if !ok {
continue
}
id, _ := item[KeyItemID].(string)
collectPaths(cf.child, item, path+"."+id+".", out)
}
}
}