Repository navigation
Expand file tree
/
Copy pathrule-validator.test.ts
More file actions
2760 lines (2538 loc) · 124 KB
/
Copy pathrule-validator.test.ts
File metadata and controls
2760 lines (2538 loc) · 124 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect } from 'vitest';
import {
evaluateValidationRules,
needsPriorRecord,
legalNextStates,
stripReadonlyWhenFields,
stripReadonlyWhenFieldsMulti,
hasReadonlyWhenInPayload,
hasParentScopedReadonlyWhenInPayload,
hasParentScopedRequiredWhen,
stripReadonlyFields,
stripRuntimeOwnedFields,
isRuntimeOwnedField,
runtimeOwnedStripWarning,
readonlyStripWarning,
} from './rule-validator.js';
import { ValidationError } from './record-validator.js';
// [#10126] Pay the first transform of these dist-resolved workspace deps at MODULE
// LOAD. Each is reached below through a dynamic `import()` inside an `it()` body or a
// hook -- both of which vitest clocks, while collection is clocked against nothing. See
// `scripts/check-test-source-alias.mjs` (the clocked-window rule) and #10115 / PR #10120,
// where the same shape cost 30 ejected merge-queue builds in one night.
import '@objectstack/spec';
// B2 — field-level conditional rules (CEL over `record`).
const invoiceFields = {
fields: {
status: { type: 'select' },
// amount is required once the invoice is sent, and locked once it's paid.
amount: {
type: 'currency',
requiredWhen: "record.status == 'sent'",
readonlyWhen: "record.status == 'paid'",
},
},
};
describe('field requiredWhen enforcement (B2)', () => {
it('rejects a missing required-when field (insert, predicate TRUE)', () => {
expect(() => evaluateValidationRules(invoiceFields, { status: 'sent' }, 'insert')).toThrow(ValidationError);
});
it('passes when the required-when field has a value', () => {
expect(() => evaluateValidationRules(invoiceFields, { status: 'sent', amount: 10 }, 'insert')).not.toThrow();
});
it('passes when the predicate is FALSE', () => {
expect(() => evaluateValidationRules(invoiceFields, { status: 'draft' }, 'insert')).not.toThrow();
});
// ── ADR-0113 non-regression: reject iff the MERGED state violates AND the
// PRE state complied. A write may not CREATE a violation; it need not FIX a
// pre-existing one. (The pre-ADR behavior — throwing on ANY write while a
// legacy row violates — was the lockout #3929 documented: a row from before
// the rule tightened could not be edited at all without backfilling.)
it('update that CREATES the violation is rejected — condition flipped true without the field', () => {
// pre: draft, no amount → complied. Write flips status to sent, no amount → violates.
expect(() => evaluateValidationRules(invoiceFields, { status: 'sent' }, 'update', { previous: { status: 'draft' } })).toThrow(ValidationError);
});
it('update that nulls the field out under a TRUE condition is rejected', () => {
// pre: sent + amount → complied. Write clears amount → violates.
expect(() => evaluateValidationRules(invoiceFields, { amount: null } as any, 'update', { previous: { status: 'sent', amount: 10 } })).toThrow(ValidationError);
});
it('legacy rows rest: a pre-existing violation does not block an unrelated write', () => {
// pre: sent, amount ALREADY missing → pre violated (row predates the rule).
// The write touches only `note` — leaves the violation in place, creates nothing.
expect(() => evaluateValidationRules(invoiceFields, { note: 'x' } as any, 'update', { previous: { status: 'sent' } })).not.toThrow();
});
it('a write that FIXES the legacy violation passes', () => {
expect(() => evaluateValidationRules(invoiceFields, { amount: 25 }, 'update', { previous: { status: 'sent' } })).not.toThrow();
});
// #3903 — the `conditionalRequired` alias read is RETIRED. Stored pre-17
// rows were lowered to `requiredWhen` by the ADR-0087 chain at rehydration
// (`applyConversionsToStoredItem`), so this validator only ever saw the
// canonical key; raw legacy input no longer gets a consumer-side fallback.
// [#25767] That kit was a ≤16.x retirement, and a retirement kit lives one
// protocol major past the major it retired in: at 18 the chain lowers
// nothing here any more. A row still carrying the alias is refused at the
// strict parse door (naming the protocol upgrade guide) and is for
// `os migrate meta --stored` on a release that still carried the step; this
// validator keeps ignoring the alias either way.
it('does NOT read the retired conditionalRequired alias (PD #12 — no dialect fallback)', () => {
const f = { fields: { amount: { type: 'currency', conditionalRequired: "record.status == 'sent'" } } } as any;
expect(() => evaluateValidationRules(f, { status: 'sent' }, 'insert')).not.toThrow();
});
it('[#25767] the stored-conversion chain no longer lowers the aged-out alias — the rule is enforced on the canonical key only', async () => {
const { applyConversionsToStoredItem } = await import('@objectstack/spec');
const legacyRow = {
name: 'invoice',
fields: { amount: { type: 'currency', conditionalRequired: "record.status == 'sent'" } },
};
const untouched = applyConversionsToStoredItem('object', legacyRow) as any;
// No step of the chain replays the ≤16.x kit: the alias is neither lowered
// nor read, so the rule it once spelled is not enforced from this row.
expect(untouched.fields.amount).toEqual({ type: 'currency', conditionalRequired: "record.status == 'sent'" });
expect(() => evaluateValidationRules(untouched, { status: 'sent' }, 'insert')).not.toThrow();
// The canonical spelling is what the chain hands this validator, and it is enforced.
const canonicalRow = {
name: 'invoice',
fields: { amount: { type: 'currency', requiredWhen: "record.status == 'sent'" } },
};
const converted = applyConversionsToStoredItem('object', canonicalRow) as any;
expect(converted.fields.amount.requiredWhen).toBe("record.status == 'sent'");
expect(() => evaluateValidationRules(converted, { status: 'sent' }, 'insert')).toThrow(ValidationError);
});
});
describe('stripReadonlyWhenFields (B2)', () => {
it('drops a field locked by a TRUE readonlyWhen (keeps the persisted value)', () => {
const out = stripReadonlyWhenFields(invoiceFields, { amount: 999 }, { status: 'paid', amount: 100 });
expect(out).toEqual({});
});
it('keeps the field when readonlyWhen is FALSE', () => {
const out = stripReadonlyWhenFields(invoiceFields, { amount: 999 }, { status: 'draft', amount: 100 });
expect(out).toEqual({ amount: 999 });
});
it('returns the same object when no readonlyWhen fields are touched', () => {
const d = { x: 1 };
expect(stripReadonlyWhenFields({ fields: { x: { type: 'number' } } }, d, null)).toBe(d);
});
});
// #3042 — `readonlyWhen` on the BULK (updateMany) path. One payload is applied
// to every matched row, so the strip evaluates the predicate against EACH
// matched row's prior state and drops a field locked in ≥1 of them.
describe('hasReadonlyWhenInPayload (#3042 gate)', () => {
it('is TRUE when the payload writes a readonlyWhen field', () => {
expect(hasReadonlyWhenInPayload(invoiceFields, { amount: 999 })).toBe(true);
});
it('is FALSE when the payload touches no readonlyWhen field', () => {
expect(hasReadonlyWhenInPayload(invoiceFields, { status: 'draft' })).toBe(false);
});
it('is FALSE for an object with no readonlyWhen fields at all', () => {
expect(hasReadonlyWhenInPayload({ fields: { x: { type: 'number' } } }, { x: 1 })).toBe(false);
});
});
describe('stripReadonlyWhenFieldsMulti (#3042)', () => {
it('drops the field when it is locked in EVERY matched row', () => {
const out = stripReadonlyWhenFieldsMulti(invoiceFields, { amount: 999 }, [
{ status: 'paid', amount: 100 },
{ status: 'paid', amount: 200 },
]);
expect(out).toEqual({});
});
it('drops the field when it is locked in AT LEAST ONE matched row (fail-safe for the batch)', () => {
// One draft (unlocked) + one paid (locked). A single bulk payload cannot
// write to the draft and skip the paid row, so the locked field is dropped
// for the whole batch.
const out = stripReadonlyWhenFieldsMulti(invoiceFields, { amount: 999 }, [
{ status: 'draft', amount: 100 },
{ status: 'paid', amount: 200 },
]);
expect(out).toEqual({});
});
it('KEEPS the field when NO matched row locks it (legitimate bulk edit unaffected)', () => {
const out = stripReadonlyWhenFieldsMulti(invoiceFields, { amount: 999 }, [
{ status: 'draft', amount: 100 },
{ status: 'sent', amount: 200 },
]);
expect(out).toEqual({ amount: 999 });
});
it('keeps the field when the match set is empty (0 rows updated anyway)', () => {
const d = { amount: 999 };
expect(stripReadonlyWhenFieldsMulti(invoiceFields, d, [])).toBe(d);
});
it('returns the same object when no readonlyWhen field is in the payload', () => {
const d = { status: 'draft' };
expect(stripReadonlyWhenFieldsMulti(invoiceFields, d, [{ status: 'paid' }])).toBe(d);
});
});
// #4889 — PARENT-scoped `readonlyWhen`. The showcase's invoice-line shape:
// `readonlyWhen: parent.status == 'paid'` on a detail whose master is the
// invoice header. Until #4889 the server bound only `record`/`previous`, so
// every one of these predicates faulted and the fail-open branch wrote the
// field anyway — the client grid was the only thing enforcing the lock.
const invoiceLineFields = {
fields: {
invoice: { type: 'master_detail', reference: 'showcase_invoice', required: true },
// Row-scoped — unaffected by the parent binding, and here to prove it.
description: { type: 'text', requiredWhen: 'record.quantity >= 100' },
quantity: { type: 'number', readonlyWhen: "parent.status == 'paid'" },
unit_price: { type: 'currency', readonlyWhen: "parent.status == 'paid'" },
},
};
describe('parent-scoped readonlyWhen (#4889)', () => {
const line = { id: 'l1', invoice: 'inv1', quantity: 6, unit_price: 49.99 };
it('drops the field when the master-detail header locks it', () => {
const out = stripReadonlyWhenFields(
invoiceLineFields,
{ quantity: 9999, unit_price: 0.01 },
line,
undefined,
{ id: 'inv1', status: 'paid' },
);
expect(out).toEqual({});
});
it('KEEPS the field when the header is not locked', () => {
const out = stripReadonlyWhenFields(
invoiceLineFields,
{ quantity: 9999 },
line,
undefined,
{ id: 'inv1', status: 'draft' },
);
expect(out).toEqual({ quantity: 9999 });
});
it('treats the field as LOCKED when `parent` could not be bound (fail-CLOSED)', () => {
// The pre-#4889 behaviour, and the bug: no `parent` binding ⇒ the predicate
// faults ⇒ the write used to go through. It must now be dropped.
const warnings: string[] = [];
const out = stripReadonlyWhenFields(invoiceLineFields, { quantity: 9999 }, line, {
warn: (m: string) => warnings.push(m),
} as never);
expect(out).toEqual({});
expect(warnings.some((w) => w.includes("reads 'parent'") && w.includes('LOCKED'))).toBe(true);
});
it('REFUSES a predicate that is simply broken (undeclared key) — ADR-0137 D2', () => {
// Not an unbound root — `record` IS bound, the key under it is not declared.
// #4649 left this fail-open for field predicates and #4889 did not widen
// itself into it; ADR-0137 D2 is what closed it — the write is refused,
// naming the field and the rule, and the refusal is logged too.
const warnings: string[] = [];
const entry = fieldRuleRefusal(() => stripReadonlyWhenFields(
{ fields: { amount: { type: 'currency', readonlyWhen: "record.no_such_field == 'paid'" } } },
{ amount: 999 },
{ amount: 1 },
{ warn: (m: string) => warnings.push(m) } as never,
), 'amount', 'readonlyWhen');
expect(entry.constraint).toMatchObject({ missingKey: 'no_such_field' });
expect(warnings.some((w) => w.includes("Field 'amount' readonlyWhen could not be evaluated"))).toBe(true);
expect(warnings.some((w) => w.includes('change allowed through'))).toBe(false);
});
it('leaves a RECORD-scoped lock on the same object working unchanged', () => {
// The contrast the issue drew: `record.status == 'paid'` was correct all
// along, and stays correct with a parent bound alongside it.
const headerFields = { fields: { status: { type: 'select' }, tax_rate: { type: 'number', readonlyWhen: "record.status == 'paid'" } } };
expect(stripReadonlyWhenFields(headerFields, { tax_rate: 99 }, { status: 'paid', tax_rate: 8 })).toEqual({});
expect(stripReadonlyWhenFields(headerFields, { tax_rate: 99 }, { status: 'draft', tax_rate: 8 })).toEqual({ tax_rate: 99 });
});
it('binds a DIFFERENT parent per matched row on the bulk path', () => {
const rows = [
{ id: 'l1', invoice: 'paid_inv', quantity: 1 },
{ id: 'l2', invoice: 'draft_inv', quantity: 2 },
];
const headers: Record<string, Record<string, unknown>> = {
paid_inv: { id: 'paid_inv', status: 'paid' },
draft_inv: { id: 'draft_inv', status: 'draft' },
};
// Locked in ≥1 matched row ⇒ dropped for the whole batch (#3042 rule).
expect(
stripReadonlyWhenFieldsMulti(invoiceLineFields, { quantity: 9999 }, rows, undefined,
(row) => headers[String(row?.invoice)] ?? null),
).toEqual({});
// No matched row locked ⇒ a legitimate bulk edit still lands.
expect(
stripReadonlyWhenFieldsMulti(invoiceLineFields, { quantity: 9999 }, [rows[1]!], undefined,
(row) => headers[String(row?.invoice)] ?? null),
).toEqual({ quantity: 9999 });
});
it('is fail-CLOSED on the bulk path too when a row has no resolvable parent', () => {
const out = stripReadonlyWhenFieldsMulti(
invoiceLineFields,
{ quantity: 9999 },
[{ id: 'l1', invoice: 'gone', quantity: 1 }],
undefined,
() => null,
);
expect(out).toEqual({});
});
});
describe('hasParentScopedReadonlyWhenInPayload (#4889 gate)', () => {
it('is TRUE when the payload writes a parent-scoped readonlyWhen field', () => {
expect(hasParentScopedReadonlyWhenInPayload(invoiceLineFields, { quantity: 1 })).toBe(true);
});
it('is FALSE when the payload only writes fields with no parent-scoped lock', () => {
expect(hasParentScopedReadonlyWhenInPayload(invoiceLineFields, { description: 'x' })).toBe(false);
});
it('is FALSE for a record-scoped readonlyWhen (no needless header read)', () => {
expect(hasParentScopedReadonlyWhenInPayload(invoiceFields, { amount: 1 })).toBe(false);
});
it('does not mistake a field NAMED parent_id, or a string literal, for the binding', () => {
const decoys = {
fields: {
a: { type: 'text', readonlyWhen: "record.parent_id != ''" },
b: { type: 'text', readonlyWhen: "record.kind == 'parent'" },
},
};
expect(hasParentScopedReadonlyWhenInPayload(decoys, { a: 'x', b: 'y' })).toBe(false);
});
});
// #4977 — PARENT-scoped `requiredWhen`, the mirror of the block above on the
// same field. `readonlyWhen` failing open WROTE a field that should have been
// frozen; `requiredWhen` failing open ACCEPTS a record that should have been
// rejected. Ruling (2026-08-06): bind the scope, keep fail-OPEN, gate the
// unbindable declaration at build time (option B — 422 — was NOT taken).
const sentLineFields = {
fields: {
invoice: { type: 'master_detail', reference: 'showcase_invoice', required: true },
// THE SUBJECT.
description: { type: 'text', requiredWhen: "parent.status == 'sent'" },
// Row-scoped — unaffected by the parent binding, and here to prove it.
note: { type: 'text', requiredWhen: 'record.quantity >= 100' },
quantity: { type: 'number' },
},
};
/**
* [ADR-0137 D2] The refusal a field-rule predicate that cannot be evaluated
* produces: the thrown `ValidationError`'s entry for `field`, asserted to be
* the unevaluable-rule envelope for `slot`. Fails when nothing was thrown.
*/
function fieldRuleRefusal(run: () => unknown, field: string, slot: 'requiredWhen' | 'readonlyWhen') {
let err: unknown;
try {
run();
} catch (e) {
err = e;
}
expect(err).toBeInstanceOf(ValidationError);
expect((err as ValidationError).code).toBe('VALIDATION_FAILED');
const entry = (err as ValidationError).fields.find((f) => f.field === field);
expect(entry).toMatchObject({
field,
code: 'rule_violation',
constraint: expect.objectContaining({ rule: slot, reason: 'unevaluable' }),
});
return entry!;
}
/** Collect the ValidationError field codes, or `null` when the write is accepted. */
function violations(
schema: unknown,
data: Record<string, unknown>,
mode: 'insert' | 'update',
opts: Record<string, unknown> = {},
): string[] | null {
try {
evaluateValidationRules(schema as never, data, mode, opts as never);
return null;
} catch (err) {
if (err instanceof ValidationError) return err.fields.map((f) => f.field);
throw err;
}
}
describe('parent-scoped requiredWhen (#4977)', () => {
it('REQUIRES the field when the master-detail header says so', () => {
expect(violations(sentLineFields, { invoice: 'inv1', quantity: 1 }, 'insert', {
parent: { id: 'inv1', status: 'sent' },
})).toEqual(['description']);
});
it('does NOT require it when the header does not match', () => {
expect(violations(sentLineFields, { invoice: 'inv1', quantity: 1 }, 'insert', {
parent: { id: 'inv1', status: 'draft' },
})).toBeNull();
});
it('accepts the write once the field is supplied', () => {
// `quantity` is supplied too: the row-scoped `note` rule orders it against
// 100, and over a null that faults — which since ADR-0137 D2 refuses the
// write instead of silently skipping `note`'s requirement.
expect(violations(sentLineFields, { invoice: 'inv1', description: 'seat', quantity: 1 }, 'insert', {
parent: { id: 'inv1', status: 'sent' },
})).toBeNull();
});
it('REFUSES when `parent` could not be bound — ADR-0137 D2 (option B, taken)', () => {
// The `readonlyWhen` twin resolves an unbound root to LOCKED. This arm kept
// the historical fail-open exit under #4977 and left the refusal ("option
// B") to the next review of ADR-0058 D5 — ADR-0137 is that review, and its
// D2 refuses the write, naming the field and the rule.
const warnings: string[] = [];
const entry = fieldRuleRefusal(() => evaluateValidationRules(sentLineFields as never, { invoice: 'inv1', quantity: 1 }, 'insert', {
logger: { warn: (m: string) => warnings.push(m) },
} as never), 'description', 'requiredWhen');
// The unbound header is named as such — not as the generic record/previous scope.
expect(entry.message).toContain("reads 'parent', the master-detail header");
expect(warnings.some((w) => w.includes("requiredWhen for 'description' failed to evaluate") && w.includes('write rejected'))).toBe(true);
expect(warnings.some((w) => w.includes('NOT enforced'))).toBe(false);
});
it('REFUSES a predicate that is simply broken, naming the key and not `parent`', () => {
// Not an unbound root — `record` IS bound, the key under it is undeclared.
const warnings: string[] = [];
const entry = fieldRuleRefusal(() => evaluateValidationRules(
{ fields: { amount: { type: 'currency', requiredWhen: "record.no_such_field == 'x'" } } } as never,
{ amount: 1 },
'insert',
{ logger: { warn: (m: string) => warnings.push(m) } } as never,
), 'amount', 'requiredWhen');
expect(entry.constraint).toMatchObject({ missingKey: 'no_such_field' });
expect(entry.message).not.toContain("reads 'parent'");
expect(warnings.some((w) => w.includes('— skipped'))).toBe(false);
});
it('leaves the ROW-scoped requiredWhen on the same object working unchanged', () => {
expect(violations(sentLineFields, { invoice: 'inv1', quantity: 500 }, 'insert', {
parent: { id: 'inv1', status: 'draft' },
})).toEqual(['note']);
});
// ── ADR-0113 non-regression, with a parent in scope ──────────────────────
it('lets a legacy row rest: the header ALREADY required it and it was already empty', () => {
expect(violations(sentLineFields, { quantity: 7 }, 'update', {
previous: { id: 'l1', invoice: 'inv1', description: '', quantity: 1 },
parent: { id: 'inv1', status: 'sent' },
})).toBeNull();
});
it('rejects a write that NULLS the field while the header requires it', () => {
expect(violations(sentLineFields, { description: '' }, 'update', {
previous: { id: 'l1', invoice: 'inv1', description: 'seat', quantity: 1 },
parent: { id: 'inv1', status: 'sent' },
})).toEqual(['description']);
});
it('judges a REPOINT by the header the write LANDS on, not the one it leaves', () => {
// The reason `previousParent` exists. The row complied under its draft
// header; the write moves it under a sent one. Binding the LANDING header
// to the pre-check too would read this as a pre-existing violation and let
// it rest — the acceptance hole this issue exists to close, one case in.
expect(violations(sentLineFields, { invoice: 'sent_inv' }, 'update', {
previous: { id: 'l1', invoice: 'draft_inv', description: '', quantity: 1 },
parent: { id: 'sent_inv', status: 'sent' },
previousParent: { id: 'draft_inv', status: 'draft' },
})).toEqual(['description']);
});
it('`previousParent` defaults to `parent` when the write does not repoint', () => {
// No repoint ⇒ the engine does not pay a second header read, and the
// legacy-row exemption must still apply.
expect(violations(sentLineFields, { quantity: 7 }, 'update', {
previous: { id: 'l1', invoice: 'inv1', description: '', quantity: 1 },
parent: { id: 'inv1', status: 'sent' },
})).toBeNull();
});
// ── blast radius: object-level rules at the SAME evaluation site ─────────
it('does NOT bind `parent` for object-level rules — still fail-CLOSED (#4649)', () => {
const withScriptRule = {
fields: { ...sentLineFields.fields },
validations: [{
type: 'script',
name: 'parent_in_object_rule',
message: 'nope',
condition: "parent.status == 'sent'",
}],
};
// A parent IS supplied, and the field predicate below evaluates with it —
// yet the object-level rule still faults on `parent` and still REJECTS.
expect(() => evaluateValidationRules(
withScriptRule as never,
{ invoice: 'inv1', description: 'seat' },
'insert',
{ parent: { id: 'inv1', status: 'sent' } } as never,
)).toThrow(/could not be evaluated/);
});
});
describe('hasParentScopedRequiredWhen (#4977 gate)', () => {
it('is TRUE when a field declares a parent-scoped requiredWhen', () => {
expect(hasParentScopedRequiredWhen(sentLineFields)).toBe(true);
});
it('is FALSE for record-scoped requiredWhen only (no needless header read)', () => {
expect(hasParentScopedRequiredWhen(invoiceFields)).toBe(false);
});
it('is FALSE for a parent-scoped READONLYWhen — that is the other gate', () => {
expect(hasParentScopedRequiredWhen(invoiceLineFields)).toBe(false);
});
it('does not mistake a field NAMED parent_id, or a string literal, for the binding', () => {
expect(hasParentScopedRequiredWhen({
fields: {
a: { type: 'text', requiredWhen: "record.parent_id != ''" },
b: { type: 'text', requiredWhen: "record.kind == 'parent'" },
},
})).toBe(false);
});
it('is NOT payload-filtered, unlike its readonlyWhen twin', () => {
// The whole failure `requiredWhen` catches is a field the payload OMITS, so
// filtering by `name in data` would skip exactly the writes it is for.
// (The twin takes a payload argument; this one deliberately does not.)
expect(hasParentScopedRequiredWhen(sentLineFields)).toBe(true);
expect(hasParentScopedReadonlyWhenInPayload(invoiceLineFields, { description: 'x' })).toBe(false);
});
});
// #4953 — the record a `readonlyWhen` predicate sees is TOTAL over the object's
// DECLARED fields, like the two seams that were materialised in #4649/#4770.
// Before this, `stripReadonlyWhenFields` merged `{...previous, ...data}` raw, so
// a predicate reading a declared column the DRIVER did not echo back faulted —
// and a faulting `readonlyWhen` fails open, i.e. WROTE the field the author
// declared frozen. Which columns come back is a storage property no author can
// see, so the same declaration was enforced or not depending on the driver.
const sparseLockFields = {
fields: {
notes: { type: 'text' },
approved_at: { type: 'datetime' },
// "while nothing has been approved, the amount is frozen" — the `== null`
// spelling #4649 made the supported one (and the null-guard gate prescribes).
amount: { type: 'currency', readonlyWhen: 'record.approved_at == null' },
},
};
/** A prior row from a driver that stores only the columns a write touched. */
const sparsePrior = () => ({ id: 'r1', amount: 100 });
/** The same row from a driver that returns every declared column. */
const totalPrior = (approvedAt: unknown) => ({ id: 'r1', amount: 100, notes: null, approved_at: approvedAt });
describe('readonlyWhen binds a TOTAL record (#4953)', () => {
it('evaluates `record.<declared> == null` on a SPARSE prior instead of faulting through', () => {
// THE bug. Pre-#4953: `No such key: approved_at` ⇒ fail-open ⇒ amount written.
const warnings: string[] = [];
const out = stripReadonlyWhenFields(sparseLockFields, { amount: 999 }, sparsePrior(), {
warn: (m: string) => warnings.push(m),
} as never);
expect(out).toEqual({});
expect(warnings.some((w) => w.includes('failed to evaluate'))).toBe(false);
expect(warnings.some((w) => w.includes('is read-only (readonlyWhen)'))).toBe(true);
});
it('still KEEPS the change when the materialised value makes the predicate FALSE', () => {
// Materialising is not "lock everything": the row HAS an approval date, so
// the lock is off and the legitimate edit lands.
expect(
stripReadonlyWhenFields(sparseLockFields, { amount: 999 }, { id: 'r1', amount: 100, approved_at: '2026-01-01' }),
).toEqual({ amount: 999 });
});
it('reads the same verdict on a sparse prior as on a total one (the point)', () => {
// One declaration, two drivers, one answer. This equality is the guarantee;
// before #4953 the left side kept the change and the right side stripped it.
const sparse = stripReadonlyWhenFields(sparseLockFields, { amount: 999 }, sparsePrior());
const total = stripReadonlyWhenFields(sparseLockFields, { amount: 999 }, totalPrior(null));
expect(sparse).toEqual(total);
expect(sparse).toEqual({});
});
it('materialises the `previous` root too, not just `record`', () => {
const schema = { fields: { ...sparseLockFields.fields, amount: { type: 'currency', readonlyWhen: 'previous.approved_at == null' } } };
expect(stripReadonlyWhenFields(schema, { amount: 999 }, sparsePrior())).toEqual({});
expect(stripReadonlyWhenFields(schema, { amount: 999 }, { id: 'r1', amount: 100, approved_at: '2026-01-01' })).toEqual({ amount: 999 });
});
it('applies on the BULK path identically — one payload, N sparse rows', () => {
// A bulk write must not judge the same predicate by a different record
// shape than a single-id write does.
expect(stripReadonlyWhenFieldsMulti(sparseLockFields, { amount: 999 }, [sparsePrior()])).toEqual({});
// ≥1 locked row still drops it for the batch; no locked row still writes.
expect(stripReadonlyWhenFieldsMulti(sparseLockFields, { amount: 999 }, [
{ id: 'r1', amount: 1, approved_at: '2026-01-01' },
sparsePrior(),
])).toEqual({});
expect(stripReadonlyWhenFieldsMulti(sparseLockFields, { amount: 999 }, [
{ id: 'r1', amount: 1, approved_at: '2026-01-01' },
{ id: 'r2', amount: 2, approved_at: '2026-02-02' },
])).toEqual({ amount: 999 });
});
it('does NOT materialise when the prior row is not in hand (no fabrication)', () => {
// `declared-fields.ts`'s standing rule: without the persisted state,
// defaulting a declared field to null would FABRICATE a value that
// contradicts the stored row. So this case keeps the historical fault —
// which since ADR-0137 D2 REFUSES the write instead of letting the change
// through — and the engine avoids it by fetching the prior row whenever
// the object declares a readonlyWhen field (`needsPriorRecord`).
fieldRuleRefusal(() => stripReadonlyWhenFields(sparseLockFields, { amount: 999 }, null), 'amount', 'readonlyWhen');
});
it('never mutates the caller\'s prior record (it is the engine\'s hookContext.previous)', () => {
const prior = sparsePrior();
stripReadonlyWhenFields(sparseLockFields, { amount: 999 }, prior);
expect('approved_at' in prior).toBe(false);
expect('notes' in prior).toBe(false);
const rows = [sparsePrior()];
stripReadonlyWhenFieldsMulti(sparseLockFields, { amount: 999 }, rows);
expect('approved_at' in rows[0]!).toBe(false);
});
it('leaves the fault branch ALIVE — an ordering comparison still faults over a total record, and refuses', () => {
// `null < null` is `no such overload`, so materialising does not make every
// predicate evaluable. This is exactly why the null-guard gate exists —
// and since ADR-0137 D2 the fault refuses the write rather than writing it.
const entry = fieldRuleRefusal(() => stripReadonlyWhenFields(
{ fields: { ...sparseLockFields.fields, amount: { type: 'currency', readonlyWhen: 'record.notes < record.approved_at' } } },
{ amount: 999 },
sparsePrior(),
), 'amount', 'readonlyWhen');
expect(entry.constraint).toMatchObject({ hint: 'null-comparison' });
});
it('keeps an UNDECLARED key unevaluable — materialising covers declared fields only — and refuses it', () => {
// The #4649 line, unmoved: a typo must stay unevaluable so it is reported,
// not silently read as null. What ADR-0137 D2 moved is the report: the
// write is refused, naming the key, instead of the change going through.
const entry = fieldRuleRefusal(() => stripReadonlyWhenFields(
{ fields: { amount: { type: 'currency', readonlyWhen: 'record.stauts == null' } } },
{ amount: 999 },
{ id: 'r1', amount: 100 },
), 'amount', 'readonlyWhen');
expect(entry.constraint).toMatchObject({ missingKey: 'stauts' });
});
// ── the consequence that moves the OTHER way, pinned rather than discovered ──
it('`has(record.<declared>)` is uniformly TRUE — so it locks even on a sparse prior', () => {
// CEL's own rule: a materialised `null` is a PRESENT key holding null.
// `has()` therefore guards against an UNDECLARED key, not an empty value.
expect(stripReadonlyWhenFields(
{ fields: { ...sparseLockFields.fields, amount: { type: 'currency', readonlyWhen: 'has(record.approved_at)' } } },
{ amount: 999 },
sparsePrior(),
)).toEqual({});
});
it('`!has(record.<declared>)` is uniformly FALSE — a lock spelled that way STOPS locking', () => {
// The one verdict this change moves toward "allowed": pre-#4953 the sparse
// binding made `!has(...)` true and the field was stripped. It was never a
// guarantee — on a driver returning all columns the same declaration never
// locked anything — so the flip replaces a storage-dependent verdict with a
// deterministic one, and the deterministic answer is FALSE. An author who
// means "while the field is empty" writes `== null` (the spelling
// @objectstack/lint's null-guard gate prescribes).
expect(stripReadonlyWhenFields(
{ fields: { ...sparseLockFields.fields, amount: { type: 'currency', readonlyWhen: '!has(record.approved_at)' } } },
{ amount: 999 },
sparsePrior(),
)).toEqual({ amount: 999 });
});
// ── blast radius: nothing else at this write gate moves ─────────────────
it('does not touch the object-level rules — `script` / `cross_field` stay fail-CLOSED (#4649)', () => {
const withRules = {
fields: { ...sparseLockFields.fields },
validations: [
{ type: 'script', name: 'typo_rule', message: 'nope', condition: 'record.stauts == null' },
],
};
expect(() => evaluateValidationRules(withRules as never, { amount: 1 }, 'update', {
previous: { id: 'r1', amount: 100 },
} as never)).toThrow(/could not be evaluated/);
const crossField = {
fields: { ...sparseLockFields.fields },
validations: [
{ type: 'cross_field', name: 'typo_cross', message: 'nope', condition: 'record.stauts == null' },
],
};
expect(() => evaluateValidationRules(crossField as never, { amount: 1 }, 'update', {
previous: { id: 'r1', amount: 100 },
} as never)).toThrow(/could not be evaluated/);
});
it('does not disturb the #4889 parent binding: unbound root still LOCKS, and this function still materialises no header', () => {
// `parent` is a row of ANOTHER object — this function has no declared-field
// list for it — and an ABSENT parent is the signal #4889 depends on.
const warnings: string[] = [];
expect(stripReadonlyWhenFields(invoiceLineFields, { quantity: 9999 }, { id: 'l1', invoice: 'inv1' }, {
warn: (m: string) => warnings.push(m),
} as never)).toEqual({});
expect(warnings.some((w) => w.includes("reads 'parent'") && w.includes('LOCKED'))).toBe(true);
// [#6457 — RE-ANNOTATED; the verdict flipped with ADR-0137 D2, not here.]
//
// A parent that IS bound but does not carry the key is still a fault at
// THIS seam — `No such key`, not the unbound-root fault. That was the hole
// #6457 closed from the ENGINE side: its ruling materialises the header
// inside `resolveMasterDetailParent(s)`, using the MASTER object's
// declared-field table — the one thing this pure function does not and
// cannot have. So the strip's own contract is unchanged (its signature
// never grew a second field table), and a caller that hands it a genuinely
// sparse header still meets the fault.
//
// What the fault DOES moved with ADR-0137 D2: it was fail-open (the change
// went through) and now REFUSES the write. The #6457 verdict on the write
// path is pinned end-to-end in `engine-readonly-when-parent.test.ts` ("ROW
// 2 — THE FIX"), with its `requiredWhen` mirror in
// `engine-required-when-parent.test.ts`.
fieldRuleRefusal(
() => stripReadonlyWhenFields(invoiceLineFields, { quantity: 9999 }, { id: 'l1', invoice: 'inv1' }, undefined, { id: 'inv1' }),
'quantity',
'readonlyWhen',
);
});
});
// #9107 — the CONDITIONAL strip judges only the keys the CALLER supplied at
// engine entry, the same discipline #5591 gave the static strip below. The two
// helpers are pinned here at the unit level; the engine-level consequences (the
// derived-field write path, and the API-boundary lock surviving it) live in
// `engine-readonly-when-derived-writes.test.ts`.
describe('stripReadonlyWhen* — supplied-key discipline (#9107)', () => {
const lockedFields = {
fields: {
status: { type: 'text' },
amount: { type: 'number', readonlyWhen: "record.status == 'paid'" },
},
};
const paid = { status: 'paid', amount: 100 };
it('KEEPS a locked key a hook ADDED — the caller never named it', () => {
const out = stripReadonlyWhenFields(lockedFields, { amount: 999 }, paid, undefined, undefined, {
supplied: {},
});
expect(out).toEqual({ amount: 999 });
expect(out).toBe(out); // nothing dropped
});
it('KEEPS a locked key a hook OVERWROTE, even though the caller supplied it', () => {
// The caller echoed `amount` back; a hook then wrote its own value over it.
// What sits on the key now is a PLATFORM write, not a forgery.
const out = stripReadonlyWhenFields(lockedFields, { amount: 777 }, paid, undefined, undefined, {
supplied: { amount: 999 },
});
expect(out).toEqual({ amount: 777 });
});
it('STILL drops it when the hook wrote the caller value back unchanged', () => {
// Identity is the whole test: an unchanged value is indistinguishable from
// "no hook touched it", and the fail-safe direction is to strip. This is
// also what closes the laundering path — echoing a key cannot exempt it.
const out = stripReadonlyWhenFields(lockedFields, { amount: 999 }, paid, undefined, undefined, {
supplied: { amount: 999 },
});
expect(out).toEqual({});
});
it('drops a caller-forged NaN — `Object.is`, not `===`', () => {
const nanFields = {
fields: { status: { type: 'text' }, amount: { type: 'number', readonlyWhen: "record.status == 'paid'" } },
};
const out = stripReadonlyWhenFields(nanFields, { amount: Number.NaN }, paid, undefined, undefined, {
supplied: { amount: Number.NaN },
});
expect(out).toEqual({});
});
it('does not read an inherited `Object.prototype` key as caller-supplied', () => {
// `constructor` matches the machine-name regex, so it is a legal field
// name; `name in supplied` would be TRUE for it on any plain object.
const oddly = {
fields: { status: { type: 'text' }, constructor: { type: 'text', readonlyWhen: "record.status == 'paid'" } },
};
const out = stripReadonlyWhenFields(oddly, { constructor: 'hook-stamp' }, paid, undefined, undefined, {
supplied: {},
});
expect(out).toEqual({ constructor: 'hook-stamp' });
});
it('an ABSENT `supplied` judges the whole payload — the fail-SAFE default', () => {
// The pre-#9107 behaviour, deliberately kept as the default: a call site
// with no entry snapshot cannot tell a hook write from a forgery and must
// assume the forgery. Forgetting the option can only over-strip.
expect(stripReadonlyWhenFields(lockedFields, { amount: 999 }, paid)).toEqual({});
});
it('a hook-written key is not even EVALUATED — no unbound-root lock, no warn', () => {
// The fail-CLOSED unbound-root branch (#4889) exists to protect against an
// unjudgeable CALLER write. A hook write is not this strip's business at
// all, so the predicate never runs and the branch is never reached.
const parentScoped = {
fields: { quantity: { type: 'number', readonlyWhen: "parent.status == 'paid'" } },
};
const warnings: string[] = [];
const out = stripReadonlyWhenFields(parentScoped, { quantity: 9999 }, { id: 'l1' }, {
warn: (m: string) => warnings.push(m),
} as never, undefined, { supplied: {} });
expect(out).toEqual({ quantity: 9999 });
expect(warnings).toEqual([]);
});
it('the BULK strip applies the identical discipline', () => {
const rows = [{ status: 'paid', amount: 100 }, { status: 'draft', amount: 50 }];
// Hook-added ⇒ survives, even though row 1 locks the field.
expect(
stripReadonlyWhenFieldsMulti(lockedFields, { amount: 999 }, rows, undefined, undefined, { supplied: {} }),
).toEqual({ amount: 999 });
// Caller-supplied ⇒ dropped for the whole batch (locked in ≥1 row).
expect(
stripReadonlyWhenFieldsMulti(lockedFields, { amount: 999 }, rows, undefined, undefined, {
supplied: { amount: 999 },
}),
).toEqual({});
});
});
// #2948 — static `readonly:true` write enforcement (caller-supplied only).
const stampedFields = {
fields: {
title: { type: 'text' },
created_by: { type: 'lookup', readonly: true },
updated_by: { type: 'lookup', readonly: true },
},
};
describe('stripReadonlyFields (#2948)', () => {
it('drops a caller-supplied write to a static readonly field', () => {
const supplied = { title: 'x', created_by: 'attacker' };
const out = stripReadonlyFields(stampedFields, { ...supplied }, supplied);
expect(out).toEqual({ title: 'x' });
});
it('KEEPS a readonly field the caller did NOT supply (server stamp survives)', () => {
// `updated_by` was written into `data` by the audit-stamp hook, not the
// caller — it must not be stripped.
const supplied = { title: 'x' };
const out = stripReadonlyFields(stampedFields, { title: 'x', updated_by: 'u1' }, supplied);
expect(out).toEqual({ title: 'x', updated_by: 'u1' });
});
it('returns the SAME object when nothing is stripped', () => {
const d = { title: 'x' };
expect(stripReadonlyFields(stampedFields, d, { title: 'x' })).toBe(d);
});
it('drops a caller-forged readonly field even when it also carries a server stamp key', () => {
const supplied = { title: 'x', created_by: 'attacker' };
const out = stripReadonlyFields(
stampedFields,
{ title: 'x', created_by: 'attacker', updated_by: 'u1' },
supplied,
);
expect(out).toEqual({ title: 'x', updated_by: 'u1' });
});
});
// #5591 — the strip must delete the value the CALLER SUBMITTED, never the value
// that happens to sit on the key when the strip runs. The strip executes after
// `beforeUpdate`, so those two differ exactly when a hook overwrote a key the
// caller had also named — which is what silently deleted hook-written publish
// timestamps on whole-record write-backs (hotcrm#788).
describe('stripReadonlyFields — supplied VALUE identity, not just key presence (#5591)', () => {
it('KEEPS a readonly key a hook OVERWROTE, even though the caller supplied it', () => {
// The caller echoed `created_by` back; a beforeUpdate hook then wrote its
// own value over it. What is on the key now is a PLATFORM write.
const supplied = { title: 'x', created_by: 'attacker' };
const afterHooks = { title: 'x', created_by: 'hook-resolved-owner' };
const out = stripReadonlyFields(stampedFields, afterHooks, supplied);
expect(out).toEqual({ title: 'x', created_by: 'hook-resolved-owner' });
expect(out).toBe(afterHooks); // nothing dropped ⇒ same reference
});
it('STILL drops it when the hook wrote the caller value back unchanged', () => {
// Identity is the whole test: an unchanged value is indistinguishable from
// "no hook touched it", and the fail-safe direction is to strip.
const supplied = { created_by: 'attacker' };
const out = stripReadonlyFields(stampedFields, { created_by: 'attacker' }, supplied);
expect(out).toEqual({});
});
it('drops a caller-forged NaN — `Object.is`, not `===`', () => {
// `===` reports NaN !== NaN, which would read a forged NaN as "a hook
// rewrote this" and KEEP it. The one input where the loose operator
// inverts the verdict, so it is pinned rather than left to a reviewer.
const numeric = { fields: { score: { type: 'number', readonly: true } } };
const supplied = { score: Number.NaN };
const out = stripReadonlyFields(numeric, { score: Number.NaN }, supplied);
expect(out).toEqual({});
});
it('does not read an inherited `Object.prototype` key as caller-supplied', () => {
// `constructor` matches the machine-name regex, so it is a legal field
// name; `name in supplied` would be TRUE for it on any plain object and
// would strip a hook stamp. Own-property check, pinned.
const oddly = { fields: { constructor: { type: 'text', readonly: true } } };
const out = stripReadonlyFields(oddly, { constructor: 'hook-stamp' }, {});
expect(out).toEqual({ constructor: 'hook-stamp' });
});
it('KNOWN LIMIT: a hook that mutates a caller-supplied object IN PLACE is still stripped', () => {
// The snapshot is shallow, so an in-place mutation leaves identity
// unchanged and is invisible to any comparison short of a deep clone —
// which this path will not pay for on every write. Documented and pinned
// so the limit is a decision, not a surprise: a hook meaning to write a
// read-only column should ASSIGN to it.
const jsonish = { fields: { payload: { type: 'json', readonly: true } } };
const shared: Record<string, unknown> = { a: 1 };
const supplied = { payload: shared };
shared.a = 2; // the "hook" mutates in place — same reference
const out = stripReadonlyFields(jsonish, { payload: shared }, supplied);
expect(out).toEqual({});
});
});
// #3493 — a "historical" import (preserveAudit) reinstates the original
// timeline: the audit/timestamp family and author-declared business `readonly`
// fields survive the strip, while platform-managed `system` columns outside the
// audit family stay stripped (no tenancy-forging backdoor).
const historicalFields = {
fields: {
title: { type: 'text' },
created_at: { type: 'datetime', readonly: true, system: true },
created_by: { type: 'lookup', readonly: true, system: true },
updated_at: { type: 'datetime', readonly: true, system: true },
updated_by: { type: 'lookup', readonly: true, system: true },
organization_id: { type: 'lookup', readonly: true, system: true },
// author-declared business readonly field (NOT system) — e.g. a case's close time
closed_at: { type: 'datetime', readonly: true },
},
};
describe('stripReadonlyFields — preserveAudit whitelist (#3493)', () => {
it('KEEPS the caller-supplied audit/timestamp family under preserveAudit', () => {
const data = {
created_at: '2020-01-01T00:00:00Z',
created_by: 'u_creator',
updated_at: '2021-03-01T00:00:00Z',
updated_by: 'u_old',
};
const out = stripReadonlyFields(historicalFields, { ...data }, data, undefined, { preserveAudit: true });
expect(out).toEqual(data);
});
it('KEEPS an author-declared business readonly field (closed_at) under preserveAudit', () => {
const supplied = { closed_at: '2021-03-01T00:00:00Z' };
const out = stripReadonlyFields(
historicalFields,
{ ...supplied },
supplied,
undefined,
{ preserveAudit: true },
);
expect(out).toEqual({ closed_at: '2021-03-01T00:00:00Z' });
});
it('NEVER keeps the primary key — a readonly `id` is stripped even under preserveAudit (#8215)', () => {
// Every platform object declares its `id` `readonly: true` and nothing
// flags it `system` (`sys_user_preference`: `Field.text({ label:
// 'Preference ID', required: true, readonly: true })`), so the pre-#8215
// second limb read it as a business field like `closed_at` — and a
// historical import's by-id update handed `SET id = 'rec_1' WHERE id =
// 'rec_1'` to the driver: a no-op on SQL, an outright rejection on stores
// with immutable primary keys. The REST ingress folds the path id into
// every update body (#6479), so the importer never even typed the key it
// was being handed back. The address of a write is not a fact being
// restored; the whitelist stops at it.
const supplied = { id: 'rec_1', closed_at: '2021-03-01T00:00:00Z' };
const out = stripReadonlyFields(
{ fields: { ...historicalFields.fields, id: { type: 'text', readonly: true } } },
{ ...supplied },
supplied,
undefined,
{ preserveAudit: true },
);
expect(out).toEqual({ closed_at: '2021-03-01T00:00:00Z' });
});
it('…while the flag keeps doing its actual job on the same payload — timeline + business fields survive (#8215)', () => {
// The other direction, pinned so the narrowing cannot creep: #3493 scoped
// `preserveAudit` to "reinstate the original timeline", and everything in
// that scope still rides through beside a stripped `id`.
const supplied = {
id: 'rec_1',
created_at: '2020-01-01T00:00:00Z',
created_by: 'u_creator',
updated_at: '2021-03-01T00:00:00Z',
updated_by: 'u_old',
closed_at: '2021-03-01T00:00:00Z',
};
const out = stripReadonlyFields(
{ fields: { ...historicalFields.fields, id: { type: 'text', readonly: true } } },
{ ...supplied },
supplied,
undefined,
{ preserveAudit: true },
);
const { id: _address, ...reinstated } = supplied;
expect(out).toEqual(reinstated);
});
it('STILL strips a non-audit system column (organization_id) under preserveAudit — no tenancy backdoor', () => {
const supplied = { organization_id: 'org_forged', closed_at: '2021-03-01T00:00:00Z' };
const out = stripReadonlyFields(
historicalFields,
{ ...supplied },
supplied,
undefined,
{ preserveAudit: true },
);
expect(out).toEqual({ closed_at: '2021-03-01T00:00:00Z' });