Repository navigation
Expand file tree
/
Copy pathexplain-engine.test.ts
More file actions
2216 lines (2052 loc) · 113 KB
/
Copy pathexplain-engine.test.ts
File metadata and controls
2216 lines (2052 loc) · 113 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) 2026 ObjectStack. Licensed under the Apache-2.0 license.
// ADR-0090 D6 — explain engine: layer verdicts, attribution, machine artifact.
import { describe, it, expect } from 'vitest';
import { resolveUserAuthzGrants, resetPlatformAdminEmailMemo } from '@objectstack/core';
import { ExplainDecisionSchema, PermissionSetSchema } from '@objectstack/spec/security';
import { PermissionEvaluator } from './permission-evaluator';
import { explainAccess, buildContextForUser, resolveDelegatorContext, type ExplainEngineDeps } from './explain-engine';
import { RLS_DENY_FILTER } from './rls-compiler';
import { unresolvedPostureRemedy } from './unresolved-posture';
import { assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core';
import { bindCatalogFromTables, ledgerFromTables } from './__tests__/security-catalog.testkit.js';
// [commit a68c61267] `ExplainDecision.layers` is `ExplainLayer[]` — the z.INPUT shape
// (ADR-0122), in which every `.default([])` member is OPTIONAL before a parse:
// a layer's `contributors`, and a record attribution's `rules`. The engine
// always populates both, which is why the assertions below reach through `?.`
// and not `!`: an absent member arrives at the matcher as `undefined` and the
// expectation still fails loudly, so the check survives the repair. This file
// was outside every tsc program in the package until `tsconfig.test.json`.
const SALES_USER = PermissionSetSchema.parse({
name: 'sales_user',
objects: { leave_request: { allowRead: true, allowCreate: true, readScope: 'unit' } },
});
const ADMIN = PermissionSetSchema.parse({
name: 'admin_full_access',
objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true } },
systemPermissions: ['manage_users'],
});
const PRIVATE_SCHEMA = { name: 'leave_request', sharingModel: 'private' };
// The ONE engine double this file declares: a `ql` whose `findOne` resolves the
// `onBehalfOf` delegator, so D10 resolves instead of failing closed as
// 'missing' (which is a different report entirely). Shared by every test that
// needs a resolvable delegator — a second inline copy would be a second double
// for `check:engine-double-contract` to ratchet, and reusing the one the file
// already pins is cheaper than growing that ledger.
const DELEGATOR_QL = {
getSchema: () => PRIVATE_SCHEMA,
findOne: async (object: string, query?: EngineFindOneQueryInput) => {
assertEngineFindOnePredicate(object, query);
return { id: 'u_boss' };
},
find: async () => [],
};
function makeDeps(overrides: Partial<ExplainEngineDeps> & { sets?: any[]; schema?: any; rls?: any } = {}): ExplainEngineDeps {
const evaluator = new PermissionEvaluator();
return {
ql: { getSchema: () => overrides.schema ?? PRIVATE_SCHEMA },
resolveSets: async () => overrides.sets ?? [SALES_USER],
evaluator,
getObjectSecurityMeta: async () => ({
isPrivate: false,
requiredPermissions: { all: [], read: [], create: [], update: [], delete: [] },
fieldRequiredPermissions: {},
}),
requiredCaps: (meta: any, op: string) => {
const bucket = op === 'find' ? 'read' : op === 'insert' ? 'create' : op;
return [...(meta.all ?? []), ...((meta as any)[bucket] ?? [])];
},
computeRlsFilter: async () => overrides.rls !== undefined ? overrides.rls : null,
getFieldMask: () => ({}),
getPartialMaskRules: async () => ({}),
baselinePermissionSets: ['member_default'],
tenancyPosture: 'single',
...overrides,
};
}
const CTX = { userId: 'u1', positions: ['sales_rep', 'everyone'], permissions: [] };
describe('explainAccess (ADR-0090 D6)', () => {
it('allows a granted read and attributes the granting set', async () => {
const d = await explainAccess(makeDeps(), { object: 'leave_request', operation: 'read', context: CTX });
expect(d.allowed).toBe(true);
expect(d.principal).toMatchObject({ userId: 'u1', positions: ['sales_rep', 'everyone'], permissionSets: ['sales_user'] });
const crud = d.layers.find((l) => l.layer === 'object_crud')!;
expect(crud.verdict).toBe('grants');
expect(crud.contributors).toEqual([{ kind: 'permission_set', name: 'sales_user', via: 'resolved' }]);
// read decisions carry the composed machine artifact
expect('readFilter' in d).toBe(true);
});
it('reports the full pipeline in order', async () => {
const d = await explainAccess(makeDeps(), { object: 'leave_request', operation: 'read', context: CTX });
expect(d.layers.map((l) => l.layer)).toEqual([
'principal', 'required_permissions', 'object_crud', 'fls',
'owd_baseline', 'depth', 'sharing', 'vama_bypass', 'rls',
]);
});
it('denies an ungranted operation and explains which layer denied', async () => {
const d = await explainAccess(makeDeps(), { object: 'leave_request', operation: 'delete', context: CTX });
expect(d.allowed).toBe(false);
expect(d.layers.find((l) => l.layer === 'object_crud')!.verdict).toBe('denies');
});
it('surfaces the required_permissions AND-gate as the denying layer', async () => {
const deps = makeDeps({
getObjectSecurityMeta: async () => ({
isPrivate: false,
requiredPermissions: { all: ['manage_metadata'], read: [], create: [], update: [], delete: [] },
fieldRequiredPermissions: {},
}),
});
const d = await explainAccess(deps, { object: 'leave_request', operation: 'read', context: CTX });
expect(d.allowed).toBe(false);
const gate = d.layers.find((l) => l.layer === 'required_permissions')!;
expect(gate.verdict).toBe('denies');
expect(gate.detail).toContain('manage_metadata');
});
it('explains the leave_request incident shape: unset OWD reads as fail-closed private', async () => {
const d = await explainAccess(
makeDeps({ schema: { name: 'leave_request' } }), // no sharingModel declared
{ object: 'leave_request', operation: 'read', context: CTX },
);
const owd = d.layers.find((l) => l.layer === 'owd_baseline')!;
expect(owd.verdict).toBe('narrows');
expect(owd.detail).toContain('ADR-0090 D1');
});
it('reports VAMA bypass and org depth for an admin', async () => {
const d = await explainAccess(makeDeps({ sets: [ADMIN] }), { object: 'leave_request', operation: 'read', context: { userId: 'admin', positions: ['platform_admin', 'everyone'], permissions: [] } });
expect(d.allowed).toBe(true);
expect(d.layers.find((l) => l.layer === 'vama_bypass')!.verdict).toBe('widens');
expect(d.layers.find((l) => l.layer === 'depth')!.detail).toContain("'org'");
});
it('an RLS deny-all composition flips the decision to denied', async () => {
const d = await explainAccess(
makeDeps({ rls: { id: '__deny_all__' } }),
{ object: 'leave_request', operation: 'read', context: CTX },
);
expect(d.allowed).toBe(false);
expect(d.layers.find((l) => l.layer === 'rls')!.verdict).toBe('denies');
});
it('carries D10 dual attribution when the context acts on behalf of a user', async () => {
const d = await explainAccess(makeDeps(), {
object: 'leave_request', operation: 'read',
context: { ...CTX, principalKind: 'agent', onBehalfOf: { userId: 'u9' } },
});
expect(d.principal.principalKind).toBe('agent');
expect(d.principal.onBehalfOf).toEqual({ userId: 'u9' });
expect(d.layers[0].detail).toContain('on behalf of u9');
});
it('surfaces expired grants in the principal layer with the dedicated state (ADR-0091 D2)', async () => {
const d = await explainAccess(makeDeps(), {
object: 'leave_request', operation: 'read',
context: {
...CTX,
droppedGrants: [{ kind: 'position', name: 'payroll_approver', state: 'expired', until: '2026-07-01T00:00:00Z' }],
},
});
const principal = d.layers.find((l) => l.layer === 'principal')!;
expect(principal.detail).toContain('EXPIRED');
expect(principal.detail).toContain('payroll_approver until 2026-07-01T00:00:00Z');
expect(principal.contributors).toContainEqual({
kind: 'position',
name: 'payroll_approver',
via: 'held until 2026-07-01T00:00:00Z — expired',
state: 'expired',
});
// Expired grants contribute nothing to the resolved principal itself.
expect(d.principal.positions).not.toContain('payroll_approver');
});
it('surfaces deactivated grants in the principal layer with the shared held-state vocabulary (ADR-0049 / #8714)', async () => {
const d = await explainAccess(makeDeps(), {
object: 'leave_request', operation: 'read',
context: {
...CTX,
droppedGrants: [
{ kind: 'permission_set', name: 'crm_full', state: 'deactivated' },
{ kind: 'position', name: 'field_auditor', state: 'deactivated' },
],
},
});
const principal = d.layers.find((l) => l.layer === 'principal')!;
expect(principal.detail).toContain('DEACTIVATED');
expect(principal.detail).toContain('crm_full');
expect(principal.detail).toContain('field_auditor');
expect(principal.contributors).toContainEqual({
kind: 'permission_set',
name: 'crm_full',
via: 'held — deactivated',
state: 'deactivated',
});
expect(principal.contributors).toContainEqual({
kind: 'position',
name: 'field_auditor',
via: 'held — deactivated',
state: 'deactivated',
});
// Deactivated grants contribute nothing to the resolved principal itself.
expect(d.principal.permissionSets).not.toContain('crm_full');
expect(d.principal.positions).not.toContain('field_auditor');
});
it('expired and deactivated rows share ONE vocabulary — both states appear side by side in one principal layer (#8714)', async () => {
const d = await explainAccess(makeDeps(), {
object: 'leave_request', operation: 'read',
context: {
...CTX,
droppedGrants: [
{ kind: 'permission_set', name: 'quarter_close_admin', state: 'expired', until: '2026-06-01T00:00:00Z' },
{ kind: 'permission_set', name: 'crm_full', state: 'deactivated' },
],
},
});
const principal = d.layers.find((l) => l.layer === 'principal')!;
// `contributors` is the z.input type (defaulted, so optional pre-parse) —
// normalize rather than dereference. Written when this file was outside
// every tsc program and the motive was the TEST_DEBT ledger; it is the
// right shape either way, and [commit a68c61267] made it the compiler's business.
const dropped = (principal.contributors ?? []).filter((c) => c.state === 'expired' || c.state === 'deactivated');
expect(dropped).toEqual([
{ kind: 'permission_set', name: 'quarter_close_admin', via: 'held until 2026-06-01T00:00:00Z — expired', state: 'expired' },
{ kind: 'permission_set', name: 'crm_full', via: 'held — deactivated', state: 'deactivated' },
]);
expect(principal.detail).toContain('EXPIRED');
expect(principal.detail).toContain('DEACTIVATED');
});
it('attributes a delegated position "via delegation from X until Y" in the principal layer (ADR-0091 D3)', async () => {
const d = await explainAccess(makeDeps(), {
object: 'leave_request', operation: 'read',
context: {
...CTX,
positions: ['sales_rep', 'approver', 'everyone'],
delegatedPositions: [{ name: 'approver', from: 'u_boss', until: '2026-07-20T00:00:00Z' }],
},
});
const principal = d.layers.find((l) => l.layer === 'principal')!;
expect(principal.detail).toContain('held via delegation');
expect(principal.detail).toContain('approver from u_boss until 2026-07-20T00:00:00Z');
expect(principal.contributors).toContainEqual({
kind: 'position',
name: 'approver',
via: 'delegation from u_boss until 2026-07-20T00:00:00Z',
});
});
it('lists masked fields in the fls layer', async () => {
const d = await explainAccess(
makeDeps({ getFieldMask: () => ({ salary: { readable: false }, name: { readable: true } }) }),
{ object: 'leave_request', operation: 'read', context: CTX },
);
const fls = d.layers.find((l) => l.layer === 'fls')!;
expect(fls.verdict).toBe('narrows');
expect(fls.detail).toContain('salary');
});
});
// ---------------------------------------------------------------------------
// [#9127] fls — the THREE-state field mask (hidden / partially masked /
// readable). #8993 landed partial masking on the enforcement channel; this
// layer reported only the binary mask, so a gated rule field read as fully
// hidden and a gate-less rule field as fully readable. `getPartialMaskRules`
// carries the enforcement composition in (never a re-derivation), and the
// hidden/partial split here is `FieldMasker.maskResults`' own.
// ---------------------------------------------------------------------------
describe('explainAccess — fls reports partial masking (#9127)', () => {
const flsOf = async (over: Partial<ExplainEngineDeps> & { sets?: any[] }) => {
const d = await explainAccess(makeDeps(over), {
object: 'leave_request',
operation: 'read',
context: CTX,
});
return d.layers.find((l) => l.layer === 'fls')!;
};
it('HIDDEN: a field the mask denies with no applicable rule is still reported deleted', async () => {
const fls = await flsOf({
getFieldMask: () => ({ ssn: { readable: false }, name: { readable: true } }),
getPartialMaskRules: async () => ({}),
});
expect(fls.verdict).toBe('narrows');
expect(fls.detail).toContain('1 field(s) masked from responses');
expect(fls.detail).toContain('ssn');
expect(fls.detail).not.toContain('PARTIALLY');
});
it('[#25866] a row-conditioned entry (`when`) is reported AS a row-conditioned lock, not folded into the mask', async () => {
// The card's shape: `amount` is locked on approved rows only. The report
// holds no row, so it says so — which is also how every row-blind reader
// applies the entry — instead of reporting a plain lock or nothing.
const fls = await flsOf({
sets: [
{
name: 'hr_user',
objects: { leave_request: { allowRead: true, allowEdit: true } },
fields: { 'leave_request.amount': { readable: true, editable: false, when: "status == 'approved'" } },
},
] as any,
getFieldMask: () => ({}),
getPartialMaskRules: async () => ({}),
});
expect(fls.verdict).toBe('not_applicable');
expect(fls.detail).toContain('No field-level masking applies.');
expect(fls.detail).toContain('1 field permission(s) carry a row condition');
expect(fls.detail).toContain('judged per row by the write gate');
expect(fls.detail).toContain(`amount (locked when status == 'approved', set "hr_user")`);
});
// [#29610 / ruling of record 6573563853, letter A] A set holding Modify All
// on the object votes editable on every field after the per-entry vote, under
// every `when` verdict, so for that caller a conditioned lock binds on no row.
// The report reads the SAME vote (`superuserFieldVote` through
// `conditionedFieldEntries`), never a second copy of it.
const CONDITIONED_AMOUNT = {
'leave_request.amount': { readable: true, editable: false, when: "status == 'approved'" },
};
it('[#29610] a Modify All set supersedes a row-conditioned lock: the entry is reported as binding on no row', async () => {
const fls = await flsOf({
sets: [
{
name: 'hr_user',
objects: { leave_request: { allowRead: true, allowEdit: true } },
fields: CONDITIONED_AMOUNT,
},
{
name: 'hr_admin',
objects: { leave_request: { allowRead: true, allowEdit: true, viewAllRecords: true, modifyAllRecords: true } },
},
] as any,
});
expect(fls.verdict).toBe('not_applicable');
expect(fls.detail).not.toContain('judged per row by the write gate');
expect(fls.detail).toContain('1 row-conditioned field permission(s) are superseded by the Modify All Data field vote [hr_admin]');
expect(fls.detail).toContain('binds on no row');
expect(fls.detail).toContain(`amount (locked when status == 'approved', set "hr_user")`);
});
it('[#29610] a View All set does NOT supersede it: the edit lock still binds per row (read-side control)', async () => {
const fls = await flsOf({
sets: [
{
name: 'hr_user',
objects: { leave_request: { allowRead: true, allowEdit: true } },
fields: CONDITIONED_AMOUNT,
},
{
name: 'hr_auditor',
objects: { leave_request: { allowRead: true, viewAllRecords: true } },
},
] as any,
});
expect(fls.detail).toContain('1 field permission(s) carry a row condition — judged per row by the write gate');
expect(fls.detail).toContain(`amount (locked when status == 'approved', set "hr_user")`);
expect(fls.detail).not.toContain('superseded');
});
it('[#29610] a caller without the vote keeps the row-conditioned sentence as before (control)', async () => {
const fls = await flsOf({
sets: [
{
name: 'hr_user',
objects: { leave_request: { allowRead: true, allowEdit: true } },
fields: CONDITIONED_AMOUNT,
},
] as any,
});
expect(fls.detail).toContain('1 field permission(s) carry a row condition — judged per row by the write gate');
expect(fls.detail).not.toContain('superseded');
});
it('[#25866] an entry without a `when` adds no row-condition sentence', async () => {
const fls = await flsOf({
sets: [
{
name: 'hr_user',
objects: { leave_request: { allowRead: true, allowEdit: true } },
fields: { 'leave_request.amount': { readable: true, editable: false } },
},
] as any,
});
expect(fls.detail).toBe('No field-level masking applies.');
});
it('PARTIAL (gated): a rule field the caller has not unmasked is NOT reported as hidden', async () => {
// The requiredPermissions fold marks `phone` non-readable; the rule turns
// that deletion into a replacement, so the caller receives `138****5678`,
// not an absent key. Pre-#9127 this read "1 field(s) masked from
// responses: [phone]" — the first misreport on the card.
const fls = await flsOf({
getFieldMask: () => ({ phone: { readable: false } }),
getPartialMaskRules: async () => ({ phone: 'phone' }),
});
expect(fls.verdict).toBe('narrows');
expect(fls.detail).not.toContain('masked from responses');
expect(fls.detail).toContain('1 field(s) PARTIALLY masked');
expect(fls.detail).toContain('phone (phone)');
});
it('PARTIAL (gate-less): a rule with no requiredPermissions is reported, not passed over', async () => {
// No permission entry exists for `bank` — the binary mask is silent — yet
// every non-system caller sees it masked. Pre-#9127 this layer answered
// `not_applicable` / "No field-level masking applies": the second misreport.
const fls = await flsOf({
getFieldMask: () => ({}),
getPartialMaskRules: async () => ({ bank: 'bank_account' }),
});
expect(fls.verdict).toBe('narrows');
expect(fls.detail).not.toBe('No field-level masking applies.');
expect(fls.detail).toContain('1 field(s) PARTIALLY masked');
expect(fls.detail).toContain('bank (bank_account)');
});
it('READABLE: a field in neither set appears in neither list', async () => {
const fls = await flsOf({
getFieldMask: () => ({ ssn: { readable: false }, name: { readable: true } }),
getPartialMaskRules: async () => ({ phone: 'phone' }),
});
expect(fls.detail).toContain('masked from responses: [ssn]');
expect(fls.detail).toContain('PARTIALLY masked');
expect(fls.detail).not.toContain('name');
});
it('reports all three states together, splitting hidden from partially masked', async () => {
const fls = await flsOf({
getFieldMask: () => ({
ssn: { readable: false },
phone: { readable: false },
name: { readable: true },
}),
getPartialMaskRules: async () => ({ phone: 'phone', bank: 'bank_account' }),
});
expect(fls.verdict).toBe('narrows');
// `phone` is denied by the binary mask AND carries a rule → partial, not hidden.
expect(fls.detail).toContain('1 field(s) masked from responses: [ssn]');
expect(fls.detail).toContain('2 field(s) PARTIALLY masked');
expect(fls.detail).toContain('phone (phone)');
expect(fls.detail).toContain('bank (bank_account)');
});
it('an explicit permission-set DENY stays HIDDEN — explain follows enforcement, it does not assume', async () => {
// A rule never widens an explicit deny, so enforcement drops such fields
// from `partialRules` before this layer sees them. The engine must report
// whatever the composition hands it rather than re-deriving "has a rule ⇒
// partial" — that second derivation is how explain drifted in the first place.
const fls = await flsOf({
getFieldMask: () => ({ phone: { readable: false } }),
getPartialMaskRules: async () => ({}),
});
expect(fls.detail).toContain('masked from responses: [phone]');
expect(fls.detail).not.toContain('PARTIALLY');
});
it('names an explicit keepHead/keepTail span rather than a preset', async () => {
const fls = await flsOf({
getPartialMaskRules: async () => ({ code: { keepHead: 2, keepTail: 2 } }),
});
expect(fls.detail).toContain('code (keepHead 2, keepTail 2)');
});
it('keeps the D10 delegator suffix when only partial masks apply', async () => {
const d = await explainAccess(
makeDeps({
ql: DELEGATOR_QL, // resolvable delegator — otherwise D10 fails closed
getPartialMaskRules: async () => ({ phone: 'phone' }),
}),
{
object: 'leave_request',
operation: 'read',
context: { ...CTX, onBehalfOf: { userId: 'u_boss' } },
},
);
const fls = d.layers.find((l) => l.layer === 'fls')!;
expect(fls.detail).toContain('PARTIALLY masked');
expect(fls.detail).toContain('D10');
});
it('stays not_applicable when neither dimension applies', async () => {
const fls = await flsOf({});
expect(fls.verdict).toBe('not_applicable');
expect(fls.detail).toBe('No field-level masking applies.');
});
it('passes the delegator sets through to the enforcement composition (D10)', async () => {
let seen: unknown = 'not-called';
await flsOf({
getPartialMaskRules: async (_sets, _object, delegatorSets) => {
seen = delegatorSets;
return {};
},
});
// No on-behalf-of in CTX → the engine must pass null, not undefined.
expect(seen).toBeNull();
});
});
describe('explainAccess — record-grained (C2 / ADR-0095)', () => {
const REC_CTX = { userId: 'u1', tenantId: 'org1', positions: ['sales_rep', 'everyone'], permissions: [] };
function recDeps(opts: {
layered?: { layer0: any; layer1: any };
record?: Record<string, unknown> | null;
sharingFilter?: unknown;
shares?: any[];
canEdit?: boolean;
sets?: any[];
schema?: any;
} = {}): ExplainEngineDeps {
const base = makeDeps({ sets: opts.sets, schema: opts.schema });
return {
...base,
computeLayeredRlsFilter: async () => opts.layered ?? { layer0: null, layer1: null },
fetchRecord: async () => (opts.record !== undefined ? opts.record : { id: 'r1', organization_id: 'org1', owner_id: 'u1' }),
sharingReadFilter: async () => (opts.sharingFilter !== undefined ? opts.sharingFilter : null),
listRecordShares: async () => opts.shares ?? [],
canEditRecord: async () => opts.canEdit ?? false,
};
}
it('leaves the object-level report byte-identical when no recordId is supplied (backward compat)', async () => {
const d = await explainAccess(recDeps(), { object: 'leave_request', operation: 'read', context: REC_CTX });
expect(d.record).toBeUndefined();
expect(d.principal).not.toHaveProperty('posture');
expect(d.layers.map((l) => l.layer)).toEqual([
'principal', 'required_permissions', 'object_crud', 'fls',
'owd_baseline', 'depth', 'sharing', 'vama_bypass', 'rls',
]);
expect(d.layers.every((l) => l.kernelTier === undefined)).toBe(true);
expect(d.layers.every((l) => l.record === undefined)).toBe(true);
});
it('prepends the tenant_isolation Layer 0, tags every layer with kernelTier, and resolves posture', async () => {
const d = await explainAccess(
recDeps({ layered: { layer0: { organization_id: 'org1' }, layer1: null }, record: { id: 'r1', organization_id: 'org1', owner_id: 'u1' } }),
{ object: 'leave_request', operation: 'read', context: REC_CTX, recordId: 'r1' },
);
expect(d.layers[0].layer).toBe('tenant_isolation');
expect(d.layers[0].kernelTier).toBe('layer_0_tenant');
expect(d.layers.find((l) => l.layer === 'rls')!.kernelTier).toBe('layer_1_business');
expect(d.principal.posture).toBe('MEMBER');
expect(d.record).toMatchObject({ recordId: 'r1', visible: true });
});
it('derives PLATFORM_ADMIN posture from the platform-grant flag', async () => {
// [#15981] Was "from the platform_admin position". The NAME is no longer
// that evidence: `positions[]` is the security axis and carries ADR-0057 D4
// `sys_user_position` names from an `apiEnabled` table, so a tenant can mint
// one spelling the built-in. `hasPlatformAdminGrant` is what
// `buildContextForUser` sets from `grants.posture === 'PLATFORM_ADMIN'`.
const d = await explainAccess(
recDeps({ sets: [ADMIN], layered: { layer0: null, layer1: null } }),
{ object: 'leave_request', operation: 'read', context: { userId: 'a1', tenantId: 'org1', positions: ['platform_admin', 'everyone'], permissions: [], hasPlatformAdminGrant: true }, recordId: 'r1' },
);
expect(d.principal.posture).toBe('PLATFORM_ADMIN');
});
it('[#15981] the platform_admin NAME alone does not — it reports MEMBER', async () => {
const d = await explainAccess(
recDeps({ sets: [ADMIN], layered: { layer0: null, layer1: null } }),
{ object: 'leave_request', operation: 'read', context: { userId: 'a1', tenantId: 'org1', positions: ['platform_admin', 'everyone'], permissions: [] }, recordId: 'r1' },
);
expect(d.principal.posture).toBe('MEMBER');
});
it('Layer 0 (the tenant wall) excludes a cross-org record — decidedBy tenant_isolation', async () => {
const d = await explainAccess(
recDeps({ layered: { layer0: { organization_id: 'org1' }, layer1: null }, record: { id: 'r1', organization_id: 'org2', owner_id: 'u1' } }),
{ object: 'leave_request', operation: 'read', context: REC_CTX, recordId: 'r1' },
);
const tenant = d.layers.find((l) => l.layer === 'tenant_isolation')!;
expect(tenant.record!.outcome).toBe('excluded');
expect(tenant.record!.rules?.[0]).toMatchObject({ kind: 'tenant_filter', effect: 'excludes' });
expect(d.record).toMatchObject({ visible: false, decidedBy: 'tenant_isolation' });
});
it('Layer 1 (business RLS) excludes a non-matching record — decidedBy rls', async () => {
const d = await explainAccess(
recDeps({ layered: { layer0: null, layer1: { status: 'open' } }, record: { id: 'r1', organization_id: 'org1', owner_id: 'u1', status: 'closed' } }),
{ object: 'leave_request', operation: 'read', context: REC_CTX, recordId: 'r1' },
);
const rls = d.layers.find((l) => l.layer === 'rls')!;
expect(rls.record!.outcome).toBe('excluded');
expect(rls.record!.matchesRecord).toBe(false);
expect(d.record).toMatchObject({ visible: false, decidedBy: 'rls' });
});
it('a record_share admits a non-owner on a private object — sharing admits, decidedBy sharing', async () => {
const d = await explainAccess(
recDeps({
layered: { layer0: null, layer1: null },
record: { id: 'r1', organization_id: 'org1', owner_id: 'u_other' },
shares: [{ id: 'shr_1', recipient_type: 'user', recipient_id: 'u1', access_level: 'read', source: 'manual' }],
sharingFilter: { $or: [{ owner_id: 'u1' }, { id: { $in: ['r1'] } }] },
}),
{ object: 'leave_request', operation: 'read', context: REC_CTX, recordId: 'r1' },
);
const sharing = d.layers.find((l) => l.layer === 'sharing')!;
expect(sharing.record!.outcome).toBe('admitted');
expect(sharing.record!.rules?.[0]).toMatchObject({ kind: 'record_share', effect: 'admits', grants: 'read' });
expect(d.record).toMatchObject({ visible: true, decidedBy: 'sharing' });
});
// [#26180] A pending approval step the principal is on grants READ of the
// one record: the sharing service ORs its record id in, and explain names
// the request it came through — on a read, and as no grant on a write.
it('[#26180] names the pending approval request a read comes through: "via approval request N"', async () => {
const asked: unknown[] = [];
const deps = (canEdit?: boolean) => ({
...recDeps({
layered: { layer0: null, layer1: null },
record: { id: 'r1', organization_id: 'org1', owner_id: 'u_other' },
shares: [],
sharingFilter: { $or: [{ owner_id: 'u1' }, { id: { $in: ['r1'] } }] },
canEdit,
}),
listApprovalReadGrants: async (object: string, recordId: string, context: unknown) => {
asked.push([object, recordId, context]);
return ['apr_7'];
},
});
const read = await explainAccess(deps(), { object: 'leave_request', operation: 'read', context: REC_CTX, recordId: 'r1' });
const sharing = read.layers.find((l) => l.layer === 'sharing')!;
expect(sharing.record!.outcome).toBe('admitted');
expect(sharing.record!.rules).toEqual([
{ kind: 'record_share', name: 'apr_7', grants: 'read', via: 'approval request apr_7', effect: 'admits' },
]);
expect(sharing.record!.detail).toContain('via approval request apr_7');
expect(read.record).toMatchObject({ visible: true, decidedBy: 'sharing' });
// Asked with the EXPLAINED principal's context, for this record.
expect(asked).toEqual([['leave_request', 'r1', REC_CTX]]);
// A write: the same grant is evaluated, grants no write, and the gate decides.
const update = await explainAccess(deps(false), { object: 'leave_request', operation: 'update', context: REC_CTX, recordId: 'r1' });
const writeSharing = update.layers.find((l) => l.layer === 'sharing')!;
expect(writeSharing.record!.rules).toEqual([
{ kind: 'record_share', name: 'apr_7', grants: 'read', via: 'approval request apr_7', effect: 'neutral' },
]);
expect(writeSharing.record!.outcome).toBe('excluded');
expect(update.record).toMatchObject({ visible: false });
});
it('[#26180] a failing approval lookup attributes nothing and fails nothing', async () => {
const d = await explainAccess(
{
...recDeps({ layered: { layer0: null, layer1: null }, record: { id: 'r1', organization_id: 'org1', owner_id: 'u_other' }, shares: [], sharingFilter: { owner_id: 'u1' } }),
listApprovalReadGrants: async () => { throw new Error('approvals unavailable'); },
},
{ object: 'leave_request', operation: 'read', context: REC_CTX, recordId: 'r1' },
);
expect(d.layers.find((l) => l.layer === 'sharing')!.record!.rules).toEqual([]);
expect(d.record).toMatchObject({ visible: false, decidedBy: 'sharing' });
});
it('private object, non-owner, no admitting share — not visible, decidedBy sharing', async () => {
const d = await explainAccess(
recDeps({ layered: { layer0: null, layer1: null }, record: { id: 'r1', organization_id: 'org1', owner_id: 'u_other' }, shares: [], sharingFilter: { owner_id: 'u1' } }),
{ object: 'leave_request', operation: 'read', context: REC_CTX, recordId: 'r1' },
);
expect(d.layers.find((l) => l.layer === 'sharing')!.record!.outcome).toBe('excluded');
expect(d.record).toMatchObject({ visible: false, decidedBy: 'sharing' });
});
it('a missing record yields not_evaluated row layers and an invisible verdict', async () => {
const d = await explainAccess(
recDeps({ record: null }),
{ object: 'leave_request', operation: 'read', context: REC_CTX, recordId: 'missing' },
);
expect(d.record).toMatchObject({ visible: false });
expect(d.record!.decidedBy).toBeUndefined();
expect(d.layers.find((l) => l.layer === 'rls')!.record!.outcome).toBe('not_evaluated');
expect(d.layers.find((l) => l.layer === 'tenant_isolation')!.record!.outcome).toBe('not_evaluated');
});
it('write ops use the sharing service canEdit as the by-construction verdict', async () => {
const editor = PermissionSetSchema.parse({ name: 'editor', objects: { leave_request: { allowRead: true, allowEdit: true } } });
const d = await explainAccess(
recDeps({ sets: [editor], layered: { layer0: null, layer1: null }, record: { id: 'r1', organization_id: 'org1', owner_id: 'u_other' }, canEdit: true, shares: [] }),
{ object: 'leave_request', operation: 'update', context: REC_CTX, recordId: 'r1' },
);
expect(d.layers.find((l) => l.layer === 'sharing')!.record!.outcome).toBe('admitted');
expect(d.record).toMatchObject({ recordId: 'r1', visible: true });
});
// ── [ADR-0142 D3/D4] the queue story on the sharing layer ──────────────
const QUEUED_ROW = { id: 'r1', organization_id: 'org1', owner_id: null, queue: 'support_intake' };
const queueMember = (members: string[]) => async (userId: string, queue: string, org: string | null) =>
queue === 'support_intake' && org === 'org1' && members.includes(userId);
it('[ADR-0142 D3] a record sitting in a queue reports queue_membership — admits a member', async () => {
const d = await explainAccess(
{ ...recDeps({ layered: { layer0: null, layer1: null }, record: QUEUED_ROW }), queueMember: queueMember(['u1']) },
{ object: 'leave_request', operation: 'read', context: REC_CTX, recordId: 'r1' },
);
const rules = d.layers.find((l) => l.layer === 'sharing')!.record!.rules ?? [];
expect(rules).toContainEqual(expect.objectContaining({ kind: 'queue_membership', name: 'support_intake', effect: 'admits' }));
expect(ExplainDecisionSchema.safeParse(d).success).toBe(true);
});
it('[ADR-0142 D3] a non-member is reported neutral, an owned record reports no queue rule at all', async () => {
const outsider = await explainAccess(
{ ...recDeps({ layered: { layer0: null, layer1: null }, record: QUEUED_ROW }), queueMember: queueMember(['u2']) },
{ object: 'leave_request', operation: 'read', context: REC_CTX, recordId: 'r1' },
);
expect(outsider.layers.find((l) => l.layer === 'sharing')!.record!.rules)
.toContainEqual(expect.objectContaining({ kind: 'queue_membership', effect: 'neutral' }));
const owned = await explainAccess(
{ ...recDeps({ layered: { layer0: null, layer1: null }, record: { ...QUEUED_ROW, owner_id: 'u9' } }), queueMember: queueMember(['u1']) },
{ object: 'leave_request', operation: 'read', context: REC_CTX, recordId: 'r1' },
);
expect((owned.layers.find((l) => l.layer === 'sharing')!.record!.rules ?? []).map((r) => r.kind)).not.toContain('queue_membership');
});
it('[ADR-0142 D4] a transfer of an unowned record reports queue_claim from the sharing verdict', async () => {
const asked: unknown[] = [];
const claimant = await explainAccess(
{
...recDeps({ layered: { layer0: null, layer1: null }, record: QUEUED_ROW }),
queueMember: queueMember(['u1']),
claimVerdict: async (o, rid) => { asked.push([o, rid]); return 'allow'; },
},
{ object: 'leave_request', operation: 'transfer', context: REC_CTX, recordId: 'r1' },
);
expect(asked).toEqual([['leave_request', 'r1']]);
expect(claimant.layers.find((l) => l.layer === 'sharing')!.record!.rules)
.toContainEqual(expect.objectContaining({ kind: 'queue_claim', name: 'support_intake', effect: 'admits' }));
const refused = await explainAccess(
{ ...recDeps({ layered: { layer0: null, layer1: null }, record: QUEUED_ROW }), claimVerdict: async () => 'abstain' },
{ object: 'leave_request', operation: 'transfer', context: REC_CTX, recordId: 'r1' },
);
expect(refused.layers.find((l) => l.layer === 'sharing')!.record!.rules)
.toContainEqual(expect.objectContaining({ kind: 'queue_claim', effect: 'neutral' }));
});
it('[ADR-0142 D3] a delete explanation reports no queue rule — queue members never delete', async () => {
const d = await explainAccess(
{
...recDeps({ layered: { layer0: null, layer1: null }, record: QUEUED_ROW }),
queueMember: queueMember(['u1']),
claimVerdict: async () => 'allow',
},
{ object: 'leave_request', operation: 'delete', context: REC_CTX, recordId: 'r1' },
);
const kinds = (d.layers.find((l) => l.layer === 'sharing')!.record!.rules ?? []).map((r) => r.kind);
expect(kinds).not.toContain('queue_membership');
expect(kinds).not.toContain('queue_claim');
});
// ── [#4647] the bypass, at row granularity ──────────────────────────────
// The report: `allowed: true` + a `vama_bypass` layer saying "ownership and
// sharing checks are skipped", sitting next to `record: { visible: false,
// decidedBy: 'sharing' }` — one payload, two opposite answers. Under the
// ruling the bypass is real, so the ROW story has to show it (and the write
// gate, which now consults the same predicate, agrees).
const VIEW_ONLY = PermissionSetSchema.parse({
name: 'compliance_auditor',
objects: { '*': { allowRead: true, allowEdit: true, viewAllRecords: true } },
});
const OWNERLESS_ROW = { id: 'r1', organization_id: 'org1', owner_id: null };
const ADMIN_CTX = { userId: 'a1', tenantId: 'org1', positions: ['platform_admin', 'everyone'], permissions: [] };
it('[#4647] Modify All Data admits an OWNERLESS private record — record verdict agrees with the top level', async () => {
const d = await explainAccess(
recDeps({
sets: [ADMIN], layered: { layer0: null, layer1: null },
record: OWNERLESS_ROW, shares: [], sharingFilter: { owner_id: 'a1' },
canEdit: true, // the fixed gate: ownership fails, the bypass admits
}),
{ object: 'leave_request', operation: 'update', context: ADMIN_CTX, recordId: 'r1' },
);
expect(d.allowed).toBe(true);
expect(d.record).toMatchObject({ visible: true, decidedBy: 'vama_bypass' });
const vama = d.layers.find((l) => l.layer === 'vama_bypass')!;
expect(vama.verdict).toBe('widens');
expect(vama.record!.outcome).toBe('admitted');
// The sharing layer credits the bypass rather than claiming a share it never saw.
expect(d.layers.find((l) => l.layer === 'sharing')!.record!.detail).toContain('Modify All Data bypass');
});
it('[#4647] View All Data alone does NOT bypass a WRITE — and the layer names the missing bit', async () => {
const d = await explainAccess(
recDeps({
sets: [VIEW_ONLY], layered: { layer0: null, layer1: null },
record: OWNERLESS_ROW, shares: [], sharingFilter: { owner_id: 'a1' },
canEdit: false, // the gate refuses: no modify bit
}),
{ object: 'leave_request', operation: 'update', context: ADMIN_CTX, recordId: 'r1' },
);
expect(d.record!.visible).toBe(false);
const vama = d.layers.find((l) => l.layer === 'vama_bypass')!;
expect(vama.verdict).toBe('not_applicable');
expect(vama.detail).toContain('View All Data');
expect(vama.detail).toContain('Modify All Data');
expect(vama.contributors).toEqual([]);
});
it('[#4647] the same View All Data set DOES bypass a READ of that record', async () => {
const d = await explainAccess(
recDeps({
sets: [VIEW_ONLY], layered: { layer0: null, layer1: null },
record: OWNERLESS_ROW, shares: [], sharingFilter: { owner_id: 'a1' },
}),
{ object: 'leave_request', operation: 'read', context: ADMIN_CTX, recordId: 'r1' },
);
const vama = d.layers.find((l) => l.layer === 'vama_bypass')!;
expect(vama.verdict).toBe('widens');
expect(vama.contributors?.map((c) => c.name)).toEqual(['compliance_auditor']);
expect(d.record).toMatchObject({ visible: true, decidedBy: 'vama_bypass' });
});
// ── read depth, at row granularity ──────────────────────────────────────
// The sharing read filter is one predicate carrying two grants: the
// owner-match the read depth widens, OR-ed with the caller's own shares. A
// row the filter admits with no share and no ownership behind it was admitted
// by the depth, and the report names the depth layer, not sharing.
describe('read depth admits a row that no share does', () => {
const ORG_READER = PermissionSetSchema.parse({
name: 'org_reader',
objects: { leave_request: { allowRead: true, readScope: 'org' } },
});
const NOT_MINE = { id: 'r1', organization_id: 'org1', owner_id: 'u_other' };
const RULE_SHARE = {
id: 'shr_rule', recipient_type: 'user', recipient_id: 'u1', access_level: 'read' as const,
source: 'rule', source_id: 'rule_open_requests',
};
const layerRecord = (d: { layers: Array<{ layer: string; record?: any }> }, layer: string) =>
d.layers.find((l) => l.layer === layer)!.record!;
const read = (deps: ExplainEngineDeps, context: any = REC_CTX) =>
explainAccess(deps, { object: 'leave_request', operation: 'read', context, recordId: 'r1' });
it("org depth: the row explains as decidedBy 'depth', with a depth-layer record block", async () => {
// At org depth plugin-sharing composes no owner-match: the filter is null.
const d = await read(recDeps({ sets: [ORG_READER], record: NOT_MINE, shares: [], sharingFilter: null }));
expect(d.record).toMatchObject({ visible: true, decidedBy: 'depth' });
const depth = layerRecord(d, 'depth');
expect(depth.outcome).toBe('admitted');
expect(depth.detail).toContain("read depth 'org'");
const sharing = layerRecord(d, 'sharing');
expect(sharing.outcome).not.toBe('admitted');
expect(sharing.detail).not.toContain('access is granted');
expect(sharing.detail).toContain('see the depth layer');
});
it("unit depth: an owner inside the caller's unit explains as 'depth', naming the owner", async () => {
const d = await read(recDeps({ record: NOT_MINE, shares: [], sharingFilter: { owner_id: { $in: ['u1', 'u_other'] } } }));
expect(d.record).toMatchObject({ visible: true, decidedBy: 'depth' });
expect(layerRecord(d, 'depth').outcome).toBe('admitted');
expect(layerRecord(d, 'depth').detail).toContain("owner (u_other) is inside the caller's 'unit' read depth");
expect(layerRecord(d, 'sharing').outcome).toBe('not_evaluated');
});
it("unit depth: an owner outside the caller's unit is excluded by the depth layer too", async () => {
const d = await read(recDeps({ record: NOT_MINE, shares: [], sharingFilter: { owner_id: { $in: ['u1'] } } }));
expect(d.record).toMatchObject({ visible: false, decidedBy: 'sharing' });
expect(layerRecord(d, 'depth').outcome).toBe('excluded');
expect(layerRecord(d, 'sharing').outcome).toBe('excluded');
});
// [#26188] With no hierarchy resolver the sharing service evaluates 'unit'
// as 'own' (an owner-only filter), so the depth cell names the absent
// resolver, not the caller's unit. A resolver mounted reads as before.
it("unit depth, no hierarchy resolver: the depth cell names the absent resolver, not the depth", async () => {
const deps = { ...recDeps({ record: NOT_MINE, shares: [], sharingFilter: { owner_id: { $in: ['u1'] } } }), hierarchyResolverMounted: () => false };
const d = await read(deps);
expect(d.record).toMatchObject({ visible: false, decidedBy: 'sharing' });
const depth = layerRecord(d, 'depth');
expect(depth.outcome).toBe('excluded');
expect(depth.detail).toMatch(/^Hierarchy resolver absent — requires enterprise; depth evaluated as 'own'\./);
expect(depth.detail).not.toContain("outside the caller's");
});
it("unit depth, hierarchy resolver mounted: an owner outside the unit is still blamed on the depth", async () => {
const deps = { ...recDeps({ record: NOT_MINE, shares: [], sharingFilter: { owner_id: { $in: ['u1'] } } }), hierarchyResolverMounted: () => true };
const depth = layerRecord(await read(deps), 'depth');
expect(depth.outcome).toBe('excluded');
expect(depth.detail).toContain("owner (u_other) is outside the caller's 'unit' read depth");
});
it("a criteria rule's share still explains as 'sharing', with '1 share(s) attached'", async () => {
// A criteria sharing rule materialises as a `sys_record_share` row with
// `source: 'rule'` naming the matched user (sharing-rule-service.ts).
const d = await read(recDeps({
record: NOT_MINE,
shares: [RULE_SHARE],
sharingFilter: { $or: [{ owner_id: { $in: ['u1'] } }, { id: { $in: ['r1'] } }] },
}));
expect(d.record).toMatchObject({ visible: true, decidedBy: 'sharing' });
const sharing = layerRecord(d, 'sharing');
expect(sharing.outcome).toBe('admitted');
expect(sharing.detail).toBe('1 share(s) attached; access is granted for this record.');
expect(sharing.rules?.[0]).toMatchObject({ kind: 'sharing_rule', name: 'rule_open_requests', effect: 'admits' });
});
it("a share AND org depth: 'sharing' decides, the last layer to admit; the depth layer admits as well", async () => {
const d = await read(recDeps({ sets: [ORG_READER], record: NOT_MINE, shares: [RULE_SHARE], sharingFilter: null }));
expect(d.record).toMatchObject({ visible: true, decidedBy: 'sharing' });
expect(layerRecord(d, 'depth').outcome).toBe('admitted');
});
it("a share AND unit depth: 'sharing' decides; the depth layer says it cannot separate the two", async () => {
const d = await read(recDeps({
record: NOT_MINE,
shares: [RULE_SHARE],
sharingFilter: { $or: [{ owner_id: { $in: ['u1', 'u_other'] } }, { id: { $in: ['r1'] } }] },
}));
expect(d.record).toMatchObject({ visible: true, decidedBy: 'sharing' });
expect(layerRecord(d, 'depth').outcome).toBe('not_evaluated');
expect(layerRecord(d, 'depth').detail).toContain('not separated');
});
it('below org, a null filter is the sharing service imposing nothing — not the depth', async () => {
const d = await read(recDeps({ record: NOT_MINE, shares: [], sharingFilter: null }));
expect(d.record).toMatchObject({ visible: true, decidedBy: 'sharing' });
const sharing = layerRecord(d, 'sharing');
expect(sharing.detail).toContain('imposes no owner-match');
expect(sharing.detail).not.toContain('access is granted');
expect(layerRecord(d, 'depth').outcome).toBe('not_evaluated');
});
it('an on-behalf-of read never credits the depth: its filter is asked with no depth stamped', async () => {
const d = await read(
{ ...recDeps({ record: NOT_MINE, shares: [], sharingFilter: { owner_id: { $in: ['u1', 'u_other'] } } }), ql: DELEGATOR_QL },
{ ...REC_CTX, onBehalfOf: { userId: 'u_boss' } },
);
expect(d.record?.visible).toBe(true);
expect(d.record?.decidedBy).not.toBe('depth');
expect(layerRecord(d, 'depth').outcome).toBe('not_evaluated');
expect(layerRecord(d, 'sharing').detail).not.toContain('access is granted');
});
});
// ── every published decider is reachable ────────────────────────────────
// The enum is read from the spec, never restated here: a member the spec
// gains, and no branch of the decision tree produces, fails by name until a
// scenario produces it or the ledger below says why none can.
describe('decision.record.decidedBy: each published member is produced by a branch, or ledgered', () => {
const DECIDED_BY: readonly string[] =
ExplainDecisionSchema.shape.record.unwrap().shape.decidedBy.unwrap().options;
const VIEW_ALL = PermissionSetSchema.parse({
name: 'compliance_auditor',
objects: { '*': { allowRead: true, viewAllRecords: true } },
});
const CAPS_GATED = {
isPrivate: false,
requiredPermissions: { all: [], read: ['manage_metadata'], create: [], update: [], delete: [] },
fieldRequiredPermissions: {},
};
const NOT_MINE = { id: 'r1', organization_id: 'org1', owner_id: 'u_other' };
const ask = (deps: ExplainEngineDeps, operation: 'read' | 'delete' = 'read') =>
explainAccess(deps, { object: 'leave_request', operation, context: REC_CTX, recordId: 'r1' });
const PRODUCERS: Record<string, () => Promise<{ record?: { decidedBy?: string } }>> = {
tenant_isolation: () => ask(recDeps({
layered: { layer0: { organization_id: 'org1' }, layer1: null },
record: { ...NOT_MINE, organization_id: 'org2' },
})),
required_permissions: () => ask({ ...recDeps(), getObjectSecurityMeta: async () => CAPS_GATED }),
object_crud: () => ask(recDeps(), 'delete'),
owd_baseline: () => ask(recDeps({ record: { id: 'r1', organization_id: 'org1', owner_id: 'u1' } })),
depth: () => ask(recDeps({ record: NOT_MINE, shares: [], sharingFilter: { owner_id: { $in: ['u1', 'u_other'] } } })),
sharing: () => ask(recDeps({
record: NOT_MINE,
shares: [{ id: 'shr_1', recipient_type: 'user', recipient_id: 'u1', access_level: 'read', source: 'manual' }],
sharingFilter: { $or: [{ owner_id: { $in: ['u1'] } }, { id: { $in: ['r1'] } }] },
})),
vama_bypass: () => ask(recDeps({ sets: [VIEW_ALL], record: NOT_MINE, shares: [], sharingFilter: { owner_id: 'u1' } })),
rls: () => ask(recDeps({
layered: { layer0: null, layer1: { status: 'open' } },
record: { ...NOT_MINE, owner_id: 'u1', status: 'closed' },
})),
};
const NOT_PRODUCED: Record<string, string> = {
principal:
'The principal layer resolves who is asking and which sets they hold; it never judges a row. A principal ' +
'whose grants fail to resolve (a missing or unresolvable delegator) is refused at object_crud, which is ' +
'the layer the tree names for it.',
fls:
'Field-level security masks fields of a row that is served; it never admits or removes the row, so it ' +
'cannot decide whether the row is visible.',
};
it('the producers and the ledger partition the enum exactly', () => {
for (const member of DECIDED_BY) {
const produced = member in PRODUCERS;
const ledgered = member in NOT_PRODUCED;
expect(produced || ledgered, `decidedBy member '${member}' is produced by no branch and carries no ledger reason`).toBe(true);
expect(produced && ledgered, `decidedBy member '${member}' is both produced and ledgered`).toBe(false);
}
for (const key of [...Object.keys(PRODUCERS), ...Object.keys(NOT_PRODUCED)]) {
expect(DECIDED_BY, `'${key}' is not a member of the published decidedBy enum`).toContain(key);
}
for (const [member, reason] of Object.entries(NOT_PRODUCED)) {
expect(reason.trim().length, `the ledger entry for '${member}' carries no reason`).toBeGreaterThan(0);
}
});
it.each(Object.keys(PRODUCERS))("'%s' is produced by the branch its scenario drives", async (member) => {
const d = await PRODUCERS[member]();
expect(d.record?.decidedBy).toBe(member);