Repository navigation
Expand file tree
/
Copy pathsharing-service.test.ts
More file actions
2460 lines (2217 loc) · 113 KB
/
Copy pathsharing-service.test.ts
File metadata and controls
2460 lines (2217 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) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { assertEngineDeleteDispatch } from '@objectstack/objectql';
import {
SharingService,
HIERARCHY_RESOLVER_ABSENT_NOTICE,
type SharingServiceOptions,
} from './sharing-service.js';
import { buildSharingMiddleware } from './sharing-plugin.js';
import { bootRequestContext } from './exec-context-seam.testkit.js';
import { SysRecordShare } from './objects/sys-record-share.object.js';
import { SysSharingRule } from './objects/sys-sharing-rule.object.js';
// ─────────────────────────────────────────────────────────────────────
// In-memory fake engine
// ─────────────────────────────────────────────────────────────────────
interface FakeRow {
[k: string]: any;
}
function makeFakeEngine(schemas: Record<string, any>) {
const tables: Record<string, FakeRow[]> = {};
const ensure = (name: string) => (tables[name] ??= []);
function matches(row: FakeRow, filter: any): boolean {
if (!filter || typeof filter !== 'object') return true;
// `$or` / `$and` are conjoined WITH their sibling keys, the way a real
// driver ANDs them — a short-circuiting `return` here would discard every
// sibling equality key in the same object. See #7620.
if (filter.$or && Array.isArray(filter.$or) && !filter.$or.some((f: any) => matches(row, f))) {
return false;
}
if (filter.$and && Array.isArray(filter.$and) && !filter.$and.every((f: any) => matches(row, f))) {
return false;
}
for (const [k, v] of Object.entries(filter)) {
if (k === '$or' || k === '$and') continue;
const rv = row[k];
if (v != null && typeof v === 'object' && '$in' in (v as any)) {
if (!(v as any).$in.includes(rv)) return false;
continue;
}
if (rv !== v) return false;
}
return true;
}
return {
_tables: tables,
schemas,
getSchema(name: string) { return schemas[name]; },
async find(object: string, options?: any) {
const table = ensure(object);
const filter = options?.filter ?? options?.where;
let out = table.filter(r => matches(r, filter));
if (options?.orderBy?.[0]) {
// Canonical SortNode key only (spec/data/query.zod.ts): the real
// engine strips an unknown `direction:` key and defaults to asc, so
// the mock must too — honoring both keys masks wrong-key sorts.
const { field, order } = options.orderBy[0];
out = [...out].sort((a, b) => {
const av = a[field]; const bv = b[field];
if (av === bv) return 0;
const cmp = av > bv ? 1 : -1;
return order === 'desc' ? -cmp : cmp;
});
}
return out.slice(0, options?.limit ?? 1000);
},
async insert(object: string, data: any) {
const row = { ...data };
ensure(object).push(row);
return row;
},
async update(object: string, idOrData: any, dataOrOptions?: any) {
// Engine signature is overloaded — handle the (data, options)
// shape used by SharingService.grant() where id lives on data.
const data = typeof idOrData === 'object' ? idOrData : dataOrOptions;
const id = typeof idOrData === 'object' ? idOrData.id : idOrData;
const table = ensure(object);
const i = table.findIndex(r => r.id === id);
if (i >= 0) table[i] = { ...table[i], ...data };
return table[i];
},
async delete(object: string, options?: any) {
// [#4550] Pinned to ObjectQL.delete's own dispatch predicate — see the
// note in sharing-rule.test.ts for what a looser fake cost (#4434).
assertEngineDeleteDispatch(options);
const table = ensure(object);
const id = options?.where?.id ?? options?.id;
const i = table.findIndex(r => r.id === id);
if (i >= 0) table.splice(i, 1);
return { id };
},
};
}
const ACCOUNT_SCHEMA = {
name: 'account',
sharingModel: 'private',
fields: { id: {}, name: {}, owner_id: {} },
};
const LEAD_SCHEMA = {
name: 'lead',
sharingModel: 'public_read',
fields: { id: {}, name: {}, owner_id: {} },
};
// [ADR-0090 D1] A CUSTOM object with NO sharingModel + an owner field —
// the objectui#2348 leave_request incident shape. Under the secure default
// this now resolves PRIVATE (owner-scoped), never silently public.
const UNSET_OWD_SCHEMA = {
name: 'task',
// no sharingModel — custom object ⇒ defaults to private (ADR-0090 D1)
fields: { id: {}, name: {}, owner_id: {} },
};
// A SYSTEM object with no sharingModel keeps the public fall-through
// (explicit ADR-0066 posture + bypass lists own the sys_* surface).
// Explicitly-public custom object (post-ADR-0090 D1 the only way to be public).
const EXPLICIT_PUBLIC_SCHEMA = {
name: 'task',
sharingModel: 'public_read_write',
fields: { id: {}, name: {}, owner_id: {} },
};
const SYS_UNSET_OWD_SCHEMA = {
name: 'sys_widget',
isSystem: true,
fields: { id: {}, name: {}, owner_id: {} },
};
// ADR-0056 D1 — canonical OWD vocabulary maps onto the same enforced behaviours.
const CANON_PUBLIC_READ_SCHEMA = {
name: 'kbarticle',
sharingModel: 'public_read', // canonical alias of legacy `read`
fields: { id: {}, name: {}, owner_id: {} },
};
const CANON_PUBLIC_RW_SCHEMA = {
name: 'whiteboard',
sharingModel: 'public_read_write', // canonical alias of "public" (no record filter)
fields: { id: {}, name: {}, owner_id: {} },
};
const ORPHAN_SCHEMA = {
name: 'note',
sharingModel: 'private',
// no owner_id — sharing skipped
fields: { id: {}, body: {} },
};
// ─────────────────────────────────────────────────────────────────────
describe('SharingService.buildReadFilter', () => {
let engine: ReturnType<typeof makeFakeEngine>;
let svc: SharingService;
beforeEach(() => {
engine = makeFakeEngine({
account: ACCOUNT_SCHEMA,
lead: LEAD_SCHEMA,
task: UNSET_OWD_SCHEMA,
sys_widget: SYS_UNSET_OWD_SCHEMA,
note: ORPHAN_SCHEMA,
kbarticle: CANON_PUBLIC_READ_SCHEMA,
whiteboard: CANON_PUBLIC_RW_SCHEMA,
sys_record_share: { name: 'sys_record_share' },
});
svc = new SharingService({ engine });
});
it('returns null for system context', async () => {
expect(await svc.buildReadFilter('account', { isSystem: true })).toBeNull();
});
it('returns null for objects in the bypass list', async () => {
expect(await svc.buildReadFilter('sys_user', { userId: 'u1' })).toBeNull();
});
it('[ADR-0090 D1] custom object with UNSET sharingModel defaults to PRIVATE (the objectui#2348 incident regression)', async () => {
// 张三 (u1) must NOT read 李四's records on an OWD-less custom object:
// the read filter narrows to owner_id = u1 instead of passing null.
const f = await svc.buildReadFilter('task', { userId: 'u1' });
expect(f).toEqual({ owner_id: 'u1' });
});
it('[ADR-0090 D1] system object with unset sharingModel keeps the public fall-through', async () => {
expect(await svc.buildReadFilter('sys_widget', { userId: 'u1' })).toBeNull();
});
it('[ADR-0090 D4] an unrecognised stored sharingModel fails CLOSED to private', async () => {
engine.schemas.legacy = { name: 'legacy', sharingModel: 'read_write', fields: { id: {}, owner_id: {} } } as any;
const f = await svc.buildReadFilter('legacy', { userId: 'u1' });
expect(f).toEqual({ owner_id: 'u1' });
});
it('returns null for read-only-sharing objects (writes are gated, reads are not)', async () => {
expect(await svc.buildReadFilter('lead', { userId: 'u1' })).toBeNull();
});
it('canonical public_read reads like `read` (everyone reads → no filter) [ADR-0056 D1]', async () => {
expect(await svc.buildReadFilter('kbarticle', { userId: 'u1' })).toBeNull();
});
it('canonical public_read_write is unscoped on read [ADR-0056 D1]', async () => {
expect(await svc.buildReadFilter('whiteboard', { userId: 'u1' })).toBeNull();
});
it('returns null for objects without owner_id even when private', async () => {
expect(await svc.buildReadFilter('note', { userId: 'u1' })).toBeNull();
});
it('returns deny-all for private object with no userId', async () => {
const f = await svc.buildReadFilter('account', {});
expect(f).toEqual({ id: '__deny_all__' });
});
it('returns owner-only filter when user has no explicit shares', async () => {
const f = await svc.buildReadFilter('account', { userId: 'alice' });
expect(f).toEqual({ owner_id: 'alice' });
});
it('returns owner OR shared-record filter when grants exist', async () => {
// Setup grants run as system — grant authorization has its own suite below.
await svc.grant({ object: 'account', recordId: 'a1', recipientId: 'alice' }, { isSystem: true });
await svc.grant({ object: 'account', recordId: 'a2', recipientId: 'alice', accessLevel: 'edit' }, { isSystem: true });
const f: any = await svc.buildReadFilter('account', { userId: 'alice' });
expect(f.$or).toBeDefined();
expect(f.$or[0]).toEqual({ owner_id: 'alice' });
expect(f.$or[1].id.$in.sort()).toEqual(['a1', 'a2']);
});
});
// [#26180 · ruling 6429330267, letter A] The records a pending approval step
// lets the caller READ, asked of the late-bound `approvals` service and ORed in
// beside the record shares. The derivation (who, while, where, cost) is the
// approvals service's own suite; the door, on a real boot, is dogfood's
// `approval-pending-approver-record-read`. What this level states is the
// composition: the ids join the shares on the READ filter only, and every
// failure grants nothing.
describe('[#26180] SharingService — the pending approver\'s read', () => {
let engine: ReturnType<typeof makeFakeEngine>;
const grants = (entries: Array<[string, string[]]>) => new Map<string, readonly string[]>(entries);
const serviceWith = (approvals: SharingServiceOptions['approvals']) => new SharingService({ engine, approvals });
const asked: Array<{ object: string; userId?: string }> = [];
const pendingOn = (entries: Array<[string, string[]]>) => () => ({
pendingApproverReadGrants: async (object: string, context: any) => {
asked.push({ object, userId: context?.userId });
return grants(entries);
},
});
beforeEach(() => {
engine = makeFakeEngine({
account: ACCOUNT_SCHEMA,
lead: LEAD_SCHEMA,
sys_record_share: { name: 'sys_record_share' },
});
asked.length = 0;
});
it('ORs the pending-approval record ids in beside the owner-match', async () => {
const svc = serviceWith(pendingOn([['a9', ['apr_1']]]));
expect(await svc.buildReadFilter('account', { userId: 'alice' })).toEqual({
$or: [{ owner_id: 'alice' }, { id: { $in: ['a9'] } }],
});
expect(asked).toEqual([{ object: 'account', userId: 'alice' }]);
});
it('joins the record shares, once per id', async () => {
await new SharingService({ engine }).grant({ object: 'account', recordId: 'a1', recipientId: 'alice' }, { isSystem: true });
const svc = serviceWith(pendingOn([['a1', ['apr_1']], ['a9', ['apr_2']]]));
const f: any = await svc.buildReadFilter('account', { userId: 'alice' });
expect(f.$or[0]).toEqual({ owner_id: 'alice' });
expect([...f.$or[1].id.$in].sort()).toEqual(['a1', 'a9']);
});
it('never reaches a write gate: an approver on the slate who owns nothing edits and deletes nothing', async () => {
const svc = serviceWith(pendingOn([['a9', ['apr_1']]]));
await engine.insert('account', { id: 'a9', owner_id: 'bob' });
expect(await svc.canEdit('account', 'a9', { userId: 'alice' })).toBe(false);
expect(await svc.canDelete('account', 'a9', { userId: 'alice' })).toBe(false);
expect(await svc.buildWriteFilter('account', { userId: 'alice' })).toEqual({ owner_id: 'alice' });
});
it('is not asked where the read filter imposes nothing, or denies all', async () => {
const svc = serviceWith(pendingOn([['a9', ['apr_1']]]));
expect(await svc.buildReadFilter('lead', { userId: 'alice' })).toBeNull();
expect(await svc.buildReadFilter('account', {})).toEqual({ id: '__deny_all__' });
expect(asked).toEqual([]);
});
it('grants nothing to an on-behalf-of principal: the grant is the person\'s own (ADR-0090 D10)', async () => {
const svc = serviceWith(pendingOn([['a9', ['apr_1']]]));
const delegated = { userId: 'agent_1', onBehalfOf: { userId: 'alice' } } as any;
expect(await svc.buildReadFilter('account', delegated)).toEqual({ owner_id: 'agent_1' });
expect(await svc.listApprovalReadGrants('account', 'a9', delegated)).toEqual([]);
expect(asked).toEqual([]);
});
it('fails closed: no service, no member, a throwing lookup or a rejected read all grant nothing', async () => {
const ownerOnly = { owner_id: 'alice' };
const warn = vi.fn();
const variants: Array<SharingServiceOptions['approvals']> = [
undefined,
() => null,
() => { throw new Error('[Kernel] Service \'approvals\' not found'); },
() => ({}),
() => ({ pendingApproverReadGrants: async () => { throw new Error('store unavailable'); } }),
];
for (const approvals of variants) {
const svc = new SharingService({ engine, approvals, logger: { warn } });
expect(await svc.buildReadFilter('account', { userId: 'alice' })).toEqual(ownerOnly);
expect(await svc.listApprovalReadGrants('account', 'a9', { userId: 'alice' })).toEqual([]);
}
// The rejected read is the one failure that is said, once per read.
expect(warn).toHaveBeenCalledTimes(2);
expect(String(warn.mock.calls[0][0])).toContain('granting none (fail-closed)');
});
it('names, for explain, the requests that grant the one record', async () => {
const svc = serviceWith(pendingOn([['a9', ['apr_1', 'apr_2']], ['a8', ['apr_3']]]));
expect(await svc.listApprovalReadGrants('account', 'a9', { userId: 'alice' })).toEqual(['apr_1', 'apr_2']);
expect(await svc.listApprovalReadGrants('account', 'a7', { userId: 'alice' })).toEqual([]);
});
});
// [ADR-0138 D3 item 6, as the maintainer's ruling C amends it — comment
// 6148183570 on #23266] The guest reaches rows through share links only, never
// through the object's sharing model: its read filter is deny-all on every
// object record sharing scopes. Share links are redeemed at their own door and
// never pass through this filter (the door-level control is in
// `packages/qa/dogfood/test/guest-grants-channel.dogfood.test.ts`).
describe('SharingService.buildReadFilter — the guest never takes the OWD branch', () => {
const GUEST = { principalKind: 'guest', positions: ['guest'], permissions: ['bound_reader'], isSystem: false } as const;
const DENY_ALL = { id: '__deny_all__' };
let svc: SharingService;
beforeEach(() => {
svc = new SharingService({
engine: makeFakeEngine({
account: ACCOUNT_SCHEMA,
lead: LEAD_SCHEMA,
whiteboard: CANON_PUBLIC_RW_SCHEMA,
line_item: {
name: 'line_item',
sharingModel: 'controlled_by_parent',
fields: { id: {}, name: {}, owner_id: {}, account: {} },
},
note: ORPHAN_SCHEMA,
sys_record_share: { name: 'sys_record_share' },
}),
});
});
for (const [object, model] of [
['account', 'private'],
['lead', 'public_read'],
['whiteboard', 'public_read_write'],
['line_item', 'controlled_by_parent'],
['note', 'private, with no owner column (the OWD-public fall-through)'],
] as const) {
it(`${model}: the guest's read filter is deny-all`, async () => {
expect(await svc.buildReadFilter(object, { ...GUEST } as any)).toEqual(DENY_ALL);
});
}
it('control: a signed-in member still takes the OWD branch — no filter on public_read and public_read_write', async () => {
expect(await svc.buildReadFilter('lead', { principalKind: 'human', userId: 'u1' } as any)).toBeNull();
expect(await svc.buildReadFilter('whiteboard', { principalKind: 'human', userId: 'u1' } as any)).toBeNull();
});
it('control: the system context is never the guest — no filter', async () => {
expect(await svc.buildReadFilter('lead', { principalKind: 'guest', isSystem: true } as any)).toBeNull();
});
});
describe('SharingService.canEdit', () => {
let engine: ReturnType<typeof makeFakeEngine>;
let svc: SharingService;
beforeEach(() => {
engine = makeFakeEngine({
account: ACCOUNT_SCHEMA,
lead: LEAD_SCHEMA,
task: EXPLICIT_PUBLIC_SCHEMA,
kbarticle: CANON_PUBLIC_READ_SCHEMA,
whiteboard: CANON_PUBLIC_RW_SCHEMA,
sys_record_share: { name: 'sys_record_share' },
});
svc = new SharingService({ engine });
engine._tables.account = [
{ id: 'a1', name: 'Acme', owner_id: 'alice' },
{ id: 'a2', name: 'Beta', owner_id: 'bob' },
];
engine._tables.lead = [
{ id: 'l1', name: 'Lead1', owner_id: 'alice' },
];
engine._tables.kbarticle = [
{ id: 'k1', name: 'KB1', owner_id: 'alice' },
];
});
it('returns true for system context', async () => {
expect(await svc.canEdit('account', 'a1', { isSystem: true })).toBe(true);
});
it('returns true for public objects', async () => {
expect(await svc.canEdit('task', 'anything', { userId: 'bob' })).toBe(true);
});
it('returns true for record owner', async () => {
expect(await svc.canEdit('account', 'a1', { userId: 'alice' })).toBe(true);
});
it('returns false for non-owner without share', async () => {
expect(await svc.canEdit('account', 'a1', { userId: 'bob' })).toBe(false);
});
it('returns false for read-only share', async () => {
await svc.grant({ object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'read' }, { isSystem: true });
expect(await svc.canEdit('account', 'a1', { userId: 'bob' })).toBe(false);
});
it('returns true for edit share', async () => {
await svc.grant({ object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'edit' }, { isSystem: true });
expect(await svc.canEdit('account', 'a1', { userId: 'bob' })).toBe(true);
});
// [#3865] Enforcement stays deliberately WIDER than authoring: `full` is no
// longer grantable, but a row persisted before the boot backfill ran still
// means `edit`. Dropping it from the gate would silently REVOKE access.
it("still honours a stored 'full' share written before it was retired", async () => {
engine._tables.sys_record_share = [
{
id: 'shr_legacy', object_name: 'account', record_id: 'a1',
recipient_type: 'user', recipient_id: 'bob', access_level: 'full',
},
];
expect(await svc.canEdit('account', 'a1', { userId: 'bob' })).toBe(true);
});
it('enforces canEdit for sharingModel=read', async () => {
expect(await svc.canEdit('lead', 'l1', { userId: 'alice' })).toBe(true);
expect(await svc.canEdit('lead', 'l1', { userId: 'bob' })).toBe(false);
});
it('canonical public_read gates writes to the owner [ADR-0056 D1]', async () => {
expect(await svc.canEdit('kbarticle', 'k1', { userId: 'alice' })).toBe(true);
expect(await svc.canEdit('kbarticle', 'k1', { userId: 'bob' })).toBe(false);
});
it('canonical public_read_write lets anyone write [ADR-0056 D1]', async () => {
expect(await svc.canEdit('whiteboard', 'anything', { userId: 'bob' })).toBe(true);
});
});
// ─────────────────────────────────────────────────────────────────────
// [#4647] Modify All Data on the WRITE gates.
//
// The reported contradiction: `security/explain` answered `allowed: true` for a
// Modify-All holder against an OWNERLESS row of a `private` object ("ownership
// and sharing checks are skipped"), while the write path returned 403 — because
// these gates never asked about the bypass, and the `__writeScope === 'org'`
// proxy they leaned on is checked only AFTER `matchesOwnerScope` has already
// refused a NULL `owner_id`. Ruling (2026-08-04): Modify All Data means an
// admin edits any record regardless of ownership, so the gate asks — through
// the SAME `hasWriteBypass` predicate explain reports.
// ─────────────────────────────────────────────────────────────────────
describe('[#4647] SharingService write gates consult Modify All Data', () => {
const OWNERLESS_ID = 'a_orphan';
let engine: ReturnType<typeof makeFakeEngine>;
/** Counts probe calls so "asked LAST, never on the fast path" is a fact, not a hope. */
let probeCalls: number;
const withBypass = (held: boolean) => {
probeCalls = 0;
return new SharingService({
engine,
securityService: () => ({
hasWriteBypass: async () => { probeCalls++; return held; },
}),
});
};
beforeEach(() => {
engine = makeFakeEngine({
account: ACCOUNT_SCHEMA,
sys_record_share: { name: 'sys_record_share' },
});
probeCalls = 0;
engine._tables.account = [
// The seed-shaped row: the platform ownership column is NULL.
{ id: OWNERLESS_ID, name: 'Seeded', owner_id: null },
{ id: 'a1', name: 'Acme', owner_id: 'alice' },
];
});
it('canEdit admits a Modify All holder on an OWNERLESS private record', async () => {
expect(await withBypass(true).canEdit('account', OWNERLESS_ID, { userId: 'admin' })).toBe(true);
});
it('canDelete admits a Modify All holder on an OWNERLESS private record', async () => {
expect(await withBypass(true).canDelete('account', OWNERLESS_ID, { userId: 'admin' })).toBe(true);
});
it("a principal WITHOUT the modify bit stays excluded (View All Data is not a write bypass)", async () => {
const svc = withBypass(false); // what hasWriteBypass answers for a view-only set
expect(await svc.canEdit('account', OWNERLESS_ID, { userId: 'auditor' })).toBe(false);
expect(await svc.canDelete('account', OWNERLESS_ID, { userId: 'auditor' })).toBe(false);
});
it('a throwing probe fails CLOSED — a broken security service never widens a write', async () => {
const svc = new SharingService({
engine,
securityService: () => ({ hasWriteBypass: async () => { throw new Error('boom'); } }),
});
expect(await svc.canEdit('account', OWNERLESS_ID, { userId: 'admin' })).toBe(false);
expect(await svc.canDelete('account', OWNERLESS_ID, { userId: 'admin' })).toBe(false);
});
it('no security service at all (no plugin-security) degrades to owner-only', async () => {
const svc = new SharingService({ engine });
expect(await svc.canEdit('account', OWNERLESS_ID, { userId: 'admin' })).toBe(false);
expect(await svc.canDelete('account', OWNERLESS_ID, { userId: 'admin' })).toBe(false);
});
it('the probe is asked LAST — ownership and an edit share never pay for it', async () => {
const svc = withBypass(true);
expect(await svc.canEdit('account', 'a1', { userId: 'alice' })).toBe(true); // owner
expect(probeCalls, 'owner fast-path does not probe').toBe(0);
await svc.grant({ object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'edit' }, { isSystem: true });
expect(await svc.canEdit('account', 'a1', { userId: 'bob' })).toBe(true); // share
expect(probeCalls, 'share branch does not probe either').toBe(0);
expect(await svc.canEdit('account', OWNERLESS_ID, { userId: 'admin' })).toBe(true);
expect(probeCalls, 'only the otherwise-denied path probes').toBe(1);
});
});
describe('[ADR-0111 D3] SharingService.canDelete — the verb boundary', () => {
let engine: ReturnType<typeof makeFakeEngine>;
let svc: SharingService;
beforeEach(() => {
engine = makeFakeEngine({
account: ACCOUNT_SCHEMA,
lead: LEAD_SCHEMA,
task: EXPLICIT_PUBLIC_SCHEMA,
note: ORPHAN_SCHEMA,
sys_record_share: { name: 'sys_record_share' },
});
svc = new SharingService({ engine });
engine._tables.account = [
{ id: 'a1', name: 'Acme', owner_id: 'alice' },
{ id: 'a2', name: 'Beta', owner_id: 'bob' },
];
});
it('system context, public objects, and owner-less objects all allow delete (matches canEdit)', async () => {
expect(await svc.canDelete('account', 'a1', { isSystem: true })).toBe(true);
expect(await svc.canDelete('task', 'anything', { userId: 'carol' })).toBe(true);
engine._tables.note = [{ id: 'n1', body: 'x' }];
expect(await svc.canDelete('note', 'n1', { userId: 'carol' })).toBe(true);
});
it('the record owner may delete', async () => {
expect(await svc.canDelete('account', 'a1', { userId: 'alice' })).toBe(true);
});
it('a non-owner without ownership may NOT delete', async () => {
expect(await svc.canDelete('account', 'a1', { userId: 'bob' })).toBe(false);
});
it('an EDIT share grants canEdit but NOT canDelete', async () => {
await svc.grant({ object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'edit' }, { isSystem: true });
expect(await svc.canEdit('account', 'a1', { userId: 'bob' })).toBe(true);
expect(await svc.canDelete('account', 'a1', { userId: 'bob' })).toBe(false);
});
it("a legacy 'full' share likewise grants edit but not delete", async () => {
engine._tables.sys_record_share = [{
id: 'shr_legacy', object_name: 'account', record_id: 'a1',
recipient_type: 'user', recipient_id: 'bob', access_level: 'full',
}];
expect(await svc.canEdit('account', 'a1', { userId: 'bob' })).toBe(true);
expect(await svc.canDelete('account', 'a1', { userId: 'bob' })).toBe(false);
});
it('Modify All (writeScope=org) may delete a record it does not own', async () => {
expect(await svc.canDelete('account', 'a1', { userId: 'admin', __writeScope: 'org' } as any)).toBe(true);
});
it('a principal-less context may not delete a private record', async () => {
expect(await svc.canDelete('account', 'a1', {})).toBe(false);
});
});
describe('SharingService.grant / listShares / revoke', () => {
let engine: ReturnType<typeof makeFakeEngine>;
let svc: SharingService;
beforeEach(() => {
engine = makeFakeEngine({ account: ACCOUNT_SCHEMA, sys_record_share: {} });
svc = new SharingService({ engine });
// [ADR-0111 D1] admin OWNS a1 — the grants below exercise the legitimate
// owner path through the management gate (unauthorized paths have their
// own suite below).
engine._tables.account = [{ id: 'a1', name: 'Acme', owner_id: 'admin' }];
});
it('creates a new grant on first call', async () => {
const r = await svc.grant(
{ object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'edit' },
{ userId: 'admin' },
);
expect(r.id).toMatch(/^shr_/);
expect(r.access_level).toBe('edit');
expect(r.granted_by).toBe('admin');
expect(engine._tables.sys_record_share.length).toBe(1);
});
it('upserts on second call with same (object, record, recipient)', async () => {
const a = await svc.grant({ object: 'account', recordId: 'a1', recipientId: 'bob' }, { userId: 'admin' });
const b = await svc.grant({ object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'edit' }, { userId: 'admin' });
expect(engine._tables.sys_record_share.length).toBe(1);
expect(b.id).toBe(a.id);
expect(b.access_level).toBe('edit');
});
// [#3865] `full` claimed "Full Access (Transfer, Share, Delete)" while both
// gates matched `edit`/`full` alike — it granted exactly `edit`. Retired from
// the authoring surface; an older client still sending it is normalised
// rather than rejected (that would revoke access it already had).
it("normalises the retired 'full' level to 'edit' instead of persisting it", async () => {
const r = await svc.grant(
{ object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'full' as any },
{ userId: 'admin' },
);
expect(r.access_level).toBe('edit');
expect(engine._tables.sys_record_share[0].access_level).toBe('edit');
});
it('rejects an unrecognised access level instead of silently persisting it', async () => {
// A level no gate matches is a grant that looks issued and enforces
// nothing — the same declared-but-inert trap `full` was (ADR-0078).
await expect(
svc.grant(
{ object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'admin' as any },
{ userId: 'admin' },
),
).rejects.toThrow(/VALIDATION_FAILED/);
// Rejected before the upsert even queries — the table is never touched.
expect(engine._tables.sys_record_share ?? []).toHaveLength(0);
});
it('listShares returns all grants on a record', async () => {
await svc.grant({ object: 'account', recordId: 'a1', recipientId: 'bob' }, { userId: 'admin' });
await svc.grant({ object: 'account', recordId: 'a1', recipientId: 'carol', accessLevel: 'edit' }, { userId: 'admin' });
const rows = await svc.listShares('account', 'a1', { userId: 'admin' });
expect(rows.length).toBe(2);
});
it('listShares returns the newest grant first', async () => {
// Regression: the query sorted with the non-canonical `direction: 'desc'`
// key, which SortNode strips — so it sorted ascending (oldest first).
engine._tables.sys_record_share = [
{ id: 'shr_old', object_name: 'account', record_id: 'a1', recipient_id: 'bob', created_at: '2026-01-01T00:00:00Z' },
{ id: 'shr_new', object_name: 'account', record_id: 'a1', recipient_id: 'carol', created_at: '2026-02-01T00:00:00Z' },
];
const rows = await svc.listShares('account', 'a1', { userId: 'admin' });
expect(rows.map(r => r.id)).toEqual(['shr_new', 'shr_old']);
});
it('revoke removes the row', async () => {
const r = await svc.grant({ object: 'account', recordId: 'a1', recipientId: 'bob' }, { userId: 'admin' });
await svc.revoke(r.id, { userId: 'admin' });
expect(engine._tables.sys_record_share.length).toBe(0);
});
it('rejects grant input missing required fields', async () => {
await expect(svc.grant({} as any, {})).rejects.toThrow(/VALIDATION_FAILED/);
await expect(svc.grant({ object: 'account' } as any, {})).rejects.toThrow(/VALIDATION_FAILED/);
await expect(svc.grant({ object: 'account', recordId: 'a1' } as any, {})).rejects.toThrow(/VALIDATION_FAILED/);
});
});
describe('buildSharingMiddleware (engine integration)', () => {
let engine: ReturnType<typeof makeFakeEngine>;
let svc: SharingService;
beforeEach(() => {
engine = makeFakeEngine({
account: ACCOUNT_SCHEMA,
lead: LEAD_SCHEMA,
task: EXPLICIT_PUBLIC_SCHEMA,
sys_record_share: {},
});
svc = new SharingService({ engine });
engine._tables.account = [
{ id: 'a1', name: 'Acme', owner_id: 'alice' },
{ id: 'a2', name: 'Beta', owner_id: 'bob' },
];
});
it('adds visibility filter on find', async () => {
const mw = buildSharingMiddleware(svc);
const ctx: any = {
object: 'account',
operation: 'find',
ast: {},
context: { userId: 'alice' },
};
await mw(ctx, async () => {});
expect(ctx.ast.where).toEqual({ owner_id: 'alice' });
});
it('skips read filter for system context', async () => {
const mw = buildSharingMiddleware(svc);
const ctx: any = {
object: 'account',
operation: 'find',
ast: {},
context: { isSystem: true },
};
await mw(ctx, async () => {});
expect(ctx.ast.where).toBeUndefined();
});
it('throws FORBIDDEN on update by non-owner', async () => {
const mw = buildSharingMiddleware(svc);
const ctx: any = {
object: 'account',
operation: 'update',
data: { id: 'a1', name: 'X' },
context: { userId: 'bob' },
};
await expect(mw(ctx, async () => {})).rejects.toMatchObject({ code: 'FORBIDDEN', status: 403 });
});
it('allows update by owner', async () => {
const mw = buildSharingMiddleware(svc);
const ctx: any = {
object: 'account',
operation: 'update',
data: { id: 'a1', name: 'X' },
context: { userId: 'alice' },
};
let nextCalled = false;
await mw(ctx, async () => { nextCalled = true; });
expect(nextCalled).toBe(true);
});
// [#27175] The by-id gate is ONE method the middleware refuses on, so a
// reader asking `admitsByIdWrite` (the record field-access answer's
// `writable`) gets the middleware's own verdict — both verbs, both ways.
it('admitsByIdWrite is the middleware\'s by-id verdict: it refuses exactly where the method answers false', async () => {
await svc.grant({ object: 'account', recordId: 'a2', recipientId: 'alice', accessLevel: 'edit' }, { isSystem: true });
const mw = buildSharingMiddleware(svc);
const passes = (operation: 'update' | 'delete', id: string, userId: string) =>
// Each verb in the shape the engine hands its middleware: an update binds the payload id, a delete `where.id`.
mw({
object: 'account', operation, context: { userId },
...(operation === 'update' ? { data: { id } } : { options: { where: { id } } }),
} as any, async () => {}).then(() => true, (e: any) => {
expect(e).toMatchObject({ code: 'FORBIDDEN', status: 403 });
return false;
});
const spy = vi.spyOn(svc, 'admitsByIdWrite');
for (const verb of ['update', 'delete'] as const) {
for (const [id, userId] of [['a1', 'alice'], ['a1', 'bob'], ['a2', 'alice'], ['a2', 'carol']] as const) {
const verdict = await svc.admitsByIdWrite('account', id, verb, { userId } as any);
expect(await passes(verb, id, userId), `${verb} ${id} as ${userId}`).toBe(verdict);
}
}
// The middleware asked the method itself, once per write.
expect(spy.mock.calls.filter((c) => c[2] === 'update')).toHaveLength(8);
// The edit share widens update, never delete (ADR-0111 D3), through the method too.
await expect(svc.admitsByIdWrite('account', 'a2', 'update', { userId: 'alice' } as any)).resolves.toBe(true);
await expect(svc.admitsByIdWrite('account', 'a2', 'delete', { userId: 'alice' } as any)).resolves.toBe(false);
});
// [ADR-0111 D3] The verb boundary: an edit-level share opens UPDATE but NOT
// delete. alice holds an edit share on a2 (owned by bob) — update passes,
// delete is refused (delete needs ownership / write depth / Modify All).
it('an edit share allows update but NOT delete (ADR-0111 D3)', async () => {
await svc.grant({ object: 'account', recordId: 'a2', recipientId: 'alice', accessLevel: 'edit' }, { isSystem: true });
const mw = buildSharingMiddleware(svc);
let updateNext = false;
await mw(
{ object: 'account', operation: 'update', data: { id: 'a2', name: 'X' }, context: { userId: 'alice' } } as any,
async () => { updateNext = true; },
);
expect(updateNext).toBe(true);
await expect(
mw(
{ object: 'account', operation: 'delete', options: { where: { id: 'a2' } }, context: { userId: 'alice' } } as any,
async () => {},
),
).rejects.toMatchObject({ code: 'FORBIDDEN', status: 403 });
});
it('the record owner may delete their own record', async () => {
const mw = buildSharingMiddleware(svc);
let nextCalled = false;
await mw(
{ object: 'account', operation: 'delete', options: { where: { id: 'a1' } }, context: { userId: 'alice' } } as any,
async () => { nextCalled = true; },
);
expect(nextCalled).toBe(true);
});
it('Modify All (writeScope=org) may delete a record it does not own', async () => {
const mw = buildSharingMiddleware(svc);
let nextCalled = false;
await mw(
{ object: 'account', operation: 'delete', options: { where: { id: 'a2' } }, context: { userId: 'admin', __writeScope: 'org' } } as any,
async () => { nextCalled = true; },
);
expect(nextCalled).toBe(true);
});
it('bulk delete scopes to owned rows ALONE — an edit share does not widen it (ADR-0111 D3)', async () => {
await svc.grant({ object: 'account', recordId: 'a2', recipientId: 'bob', accessLevel: 'edit' }, { isSystem: true });
const mw = buildSharingMiddleware(svc);
const ctx: any = {
object: 'account',
operation: 'delete',
options: { multi: true, where: {} },
ast: {},
context: { userId: 'bob' },
};
await mw(ctx, async () => {});
// bob's edit share on a2 widens a bulk UPDATE but NOT a bulk delete.
expect(ctx.ast.where).toEqual({ owner_id: 'bob' });
});
it('bulk update DOES widen by the edit share (contrast with delete)', async () => {
await svc.grant({ object: 'account', recordId: 'a2', recipientId: 'bob', accessLevel: 'edit' }, { isSystem: true });
const mw = buildSharingMiddleware(svc);
const ctx: any = {
object: 'account',
operation: 'update',
options: { multi: true, where: {} },
ast: {},
data: { status: 'x' },
context: { userId: 'bob' },
};
await mw(ctx, async () => {});
expect(ctx.ast.where).toEqual({ $or: [{ owner_id: 'bob' }, { id: { $in: ['a2'] } }] });
});
it('does not block insert', async () => {
const mw = buildSharingMiddleware(svc);
const ctx: any = {
object: 'account',
operation: 'insert',
data: { id: 'a3', owner_id: 'eve' },
context: { userId: 'eve' },
};
let nextCalled = false;
await mw(ctx, async () => { nextCalled = true; });
expect(nextCalled).toBe(true);
});
it('preserves caller-provided filter via $and', async () => {
const mw = buildSharingMiddleware(svc);
const ctx: any = {
object: 'account',
operation: 'find',
ast: { where: { name: 'Acme' } },
context: { userId: 'alice' },
};
await mw(ctx, async () => {});
expect(ctx.ast.where).toEqual({ $and: [{ name: 'Acme' }, { owner_id: 'alice' }] });
});
// ─── Bulk (multi) write owner scoping (#2982) ───────────────────
it('bulk update: injects the editable-rows filter so a non-owner cannot touch peers', async () => {
const mw = buildSharingMiddleware(svc);
const ctx: any = {
object: 'account',
operation: 'update',
options: { multi: true, where: { name: 'X' } },
ast: { where: { name: 'X' } },
data: { status: 'archived' },
context: { userId: 'bob' },
};
let nextCalled = false;
await mw(ctx, async () => { nextCalled = true; });
expect(nextCalled).toBe(true);
// bob's bulk update is constrained to rows bob owns.
expect(ctx.ast.where).toEqual({ $and: [{ name: 'X' }, { owner_id: 'bob' }] });
});
it('bulk delete: injects the owner filter (no single id to canEdit-gate)', async () => {
const mw = buildSharingMiddleware(svc);
const ctx: any = {
object: 'account',
operation: 'delete',
options: { multi: true, where: {} },
ast: {},
context: { userId: 'bob' },
};
await mw(ctx, async () => {});
expect(ctx.ast.where).toEqual({ owner_id: 'bob' });
});
it('bulk update: edit-shared records widen the editable set', async () => {
await svc.grant({ object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'edit' }, { isSystem: true });
const mw = buildSharingMiddleware(svc);
const ctx: any = {
object: 'account',
operation: 'update',
options: { multi: true, where: {} },
ast: {},
data: { status: 'x' },
context: { userId: 'bob' },
};
await mw(ctx, async () => {});
expect(ctx.ast.where).toEqual({ $or: [{ owner_id: 'bob' }, { id: { $in: ['a1'] } }] });
});
it('bulk update on a public_read (read) object is STILL owner-write-scoped', async () => {
// The crux of #2982: reads are open on a public_read object (buildReadFilter
// returns null), but writes remain owner-scoped — a distinction the old
// single-id-only gate missed for multi writes.
engine._tables.lead = [{ id: 'l1', owner_id: 'alice' }];
const mw = buildSharingMiddleware(svc);
const ctx: any = {
object: 'lead',
operation: 'update',
options: { multi: true, where: {} },
ast: {},
data: { status: 'x' },
context: { userId: 'bob' },
};
await mw(ctx, async () => {});
expect(ctx.ast.where).toEqual({ owner_id: 'bob' });
});
it('bulk update: system context is unrestricted', async () => {
const mw = buildSharingMiddleware(svc);
const ctx: any = {
object: 'account',
operation: 'update',
options: { multi: true, where: {} },
ast: {},
data: { status: 'x' },
context: { isSystem: true },
};
await mw(ctx, async () => {});
expect(ctx.ast.where).toBeUndefined();
});
it('bulk update on a fully public object: no owner filter', async () => {
const mw = buildSharingMiddleware(svc);
const ctx: any = {
object: 'task', // EXPLICIT_PUBLIC_SCHEMA
operation: 'update',
options: { multi: true, where: {} },
ast: {},
data: { status: 'x' },
context: { userId: 'bob' },
};
await mw(ctx, async () => {});
expect(ctx.ast.where).toBeUndefined();
});
});
// ─────────────────────────────────────────────────────────────────────
// [ADR-0111] Share-management authority — the #3902 reproduction.
// mallory: an ordinary signed-in user with no grants of any kind.
// alice: owner of account a1. admin: holds Modify All via the probe.
// ─────────────────────────────────────────────────────────────────────
describe('[ADR-0111 D1] SharingService.canManageShares', () => {
let engine: ReturnType<typeof makeFakeEngine>;
beforeEach(() => {
engine = makeFakeEngine({ account: ACCOUNT_SCHEMA, sys_record_share: {} });
engine._tables.account = [{ id: 'a1', name: 'Acme', owner_id: 'alice' }];
});
it('system context manages everything', async () => {
const svc = new SharingService({ engine });
expect(await svc.canManageShares('account', 'a1', { isSystem: true })).toBe(true);
});
it('the record owner manages their record', async () => {
const svc = new SharingService({ engine });
expect(await svc.canManageShares('account', 'a1', { userId: 'alice' })).toBe(true);
});
it('a non-owner without Modify All does NOT manage (fail closed, no security plugin)', async () => {
const svc = new SharingService({ engine });
expect(await svc.canManageShares('account', 'a1', { userId: 'mallory' })).toBe(false);
});