Repository navigation
Expand file tree
/
Copy pathcontrolled-by-parent-sharing.test.ts
More file actions
1277 lines (1183 loc) · 61.8 KB
/
Copy pathcontrolled-by-parent-sharing.test.ts
File metadata and controls
1277 lines (1183 loc) · 61.8 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.
//
// [#5386] `controlled_by_parent` (ADR-0055) must resolve the MASTER's
// accessibility through the SAME path a direct read / write of that master
// takes — owner scope and `sys_record_share` grants folded in, not the master's
// RLS policies alone.
//
// ## What was measured before this suite existed
//
// The derivation ran `computeRlsFilter(master, 'find')` and nothing else, under
// a system context. Owner scope and record shares are contributed by a SIBLING
// plugin (`plugin-sharing`), whose `buildReadFilter` returns `null` for any
// object whose effective sharing model is not `private` — and
// `controlled_by_parent` maps to `public` there. So the two halves of
// record-level access never met on a derived object:
//
// • an app that authors NO `rowLevelSecurity` on the master got an
// UNRESTRICTED master id set, i.e. the declared narrowing narrowed nothing
// and every detail row was readable by any holder of object-level read;
// • authoring RLS on the master was not a workaround, because RLS is ANDed
// with the sharing filter rather than OR-ed into it, so it also cut off the
// rows a grant had shared in;
// • the write half had the same hole from the other side — its master row
// check was SKIPPED WHOLE when the master's write RLS compiled to `null`.
//
// ## Why one fixture drives both faces
//
// The read filter and the write assertion are two implementation faces of ONE
// contract ("a child follows its parent's access"). A suite that exercised them
// on separate fixtures could not see them disagree, which is the failure this
// family produces: a third, quieter answer where one face allows what the other
// refuses. Every case below runs on the SAME three-account fixture — a master
// owned by someone else and shared to the caller, a master owned by someone
// else and NOT shared (the excluded row, without which "consistent" would prove
// nothing), and a master the caller owns.
import { describe, it, expect, vi } from 'vitest';
import { recordNotFoundError } from '@objectstack/core';
import { SecurityPlugin } from './security-plugin.js';
import { SharingService, type SharingEngine } from '@objectstack/plugin-sharing';
import { matchesFilterCondition } from '@objectstack/formula';
// [#8688] The REAL required-field validator, not a restatement of it. The
// conditional stand-down's whole safety argument is "validation covers this
// omission, and does not cover those" — a hand-mirrored copy of that predicate
// would assert the belief instead of the behaviour, and would keep passing on
// the day the validator's own skip list changes. This package's vitest config
// aliases `@objectstack/objectql` to `packages/objectql/src`, so this resolves
// to the source in the checkout rather than a prebuilt dist.
import { validateRecord, assertEngineFindOnePredicate } from '@objectstack/objectql';
import type { PermissionSet } from '@objectstack/spec/security';
import { ObjectSchema, controlledByParentMasterRefusal } from '@objectstack/spec/data';
import { composeReadableIdsInMemory } from './readable-ids-in-memory.testkit.js';
const REP = 'usr_rep';
const OTHER = 'usr_other';
/** The MASTER — owner-scoped by OWD (`private`), with no authored RLS at all. */
const ACCOUNT_SCHEMA = {
name: 'crm_account',
sharingModel: 'private',
fields: {
id: { name: 'id', type: 'text' },
name: { name: 'name', type: 'text' },
owner_id: { name: 'owner_id', type: 'lookup', reference: 'sys_user' },
},
};
/** The DETAIL — access derived from `crm_account` through the master_detail FK. */
const CONTACT_SCHEMA = {
name: 'crm_contact',
sharingModel: 'controlled_by_parent',
fields: {
id: { name: 'id', type: 'text' },
name: { name: 'name', type: 'text' },
account: { name: 'account', type: 'master_detail', required: true, reference: 'crm_account' },
},
};
/**
* [#7474] The same detail, AUTHORED WRONG: `controlled_by_parent` with nothing
* to derive access from — no master_detail field at all. The gate's
* metadata-defect leg is the only thing between this object and a write that
* answers a false 403.
*/
const CONTACT_SCHEMA_NO_MASTER_DETAIL = {
name: 'crm_contact',
sharingModel: 'controlled_by_parent',
fields: {
id: { name: 'id', type: 'text' },
name: { name: 'name', type: 'text' },
// A lookup, and OPTIONAL — no relation at all, before #23100 and after it
// (a required lookup no longer resolves either; see the retired tiers).
account: { name: 'account', type: 'lookup', reference: 'crm_account' },
},
};
/**
* [#8688] The declarations required-field validation does NOT cover, and the
* reason the insert-leg stand-down is conditional rather than flat.
*
* `validateRecord` (`@objectstack/objectql`) walks every declared field on an
* insert but skips provenance-flagged ones outright — `if (def.system ||
* def.readonly) continue;` — before the required check, and never fires on a
* field that is not `required` at all. On the `readonly` / `system` shapes
* below this gate is therefore the only refusal an absent master FK meets —
* the suite asserts that against the REAL validator rather than against a
* belief about it. Neither is authorable any more: the parse refuses both
* (`master-not-writable`, #25092), so they reach the runtime only through a
* door that does not parse, and there the gate refuses every insert under
* them as the declaration defect, `422 INVALID_METADATA` (#25095).
*
* [#23100] The first shape, a `master_detail` with no `required`, was the third
* member of this set while `resolveCbpRelation`'s second fallback resolved it.
* Ruling B retired that fallback, so it resolves NO relation now and meets the
* metadata-defect leg instead — pinned with the other retired tier below.
*/
const CONTACT_SCHEMA_MASTER_NOT_REQUIRED = {
name: 'crm_contact',
sharingModel: 'controlled_by_parent',
fields: {
id: { name: 'id', type: 'text' },
name: { name: 'name', type: 'text' },
account: { name: 'account', type: 'master_detail', reference: 'crm_account' },
},
};
const CONTACT_SCHEMA_MASTER_READONLY = {
name: 'crm_contact',
sharingModel: 'controlled_by_parent',
fields: {
id: { name: 'id', type: 'text' },
name: { name: 'name', type: 'text' },
account: {
name: 'account', type: 'master_detail', required: true, readonly: true, reference: 'crm_account',
},
},
};
const CONTACT_SCHEMA_MASTER_SYSTEM = {
name: 'crm_contact',
sharingModel: 'controlled_by_parent',
fields: {
id: { name: 'id', type: 'text' },
name: { name: 'name', type: 'text' },
account: {
name: 'account', type: 'master_detail', required: true, system: true, reference: 'crm_account',
},
},
};
/**
* [#8688 → #23100] `controlled_by_parent` with no `master_detail` but a
* REQUIRED lookup — `resolveCbpRelation`'s third fallback until ruling B
* retired it, and HotCRM's `crm_campaign_member` / `crm_event_attendee` /
* `crm_article_feedback` shape. It resolves no relation now.
*/
const CONTACT_SCHEMA_MASTER_REQUIRED_LOOKUP = {
name: 'crm_contact',
sharingModel: 'controlled_by_parent',
fields: {
id: { name: 'id', type: 'text' },
name: { name: 'name', type: 'text' },
account: { name: 'account', type: 'lookup', required: true, reference: 'crm_account' },
},
};
/**
* [#8688] The detail-object schema variants, keyed by the `boot({ detail })`
* selector. `valid` is the shape the ruling covers; the rest are the shapes it
* deliberately does not.
*/
/**
* [#23100] Two REQUIRED master_details: the one tie left after the retired
* tiers. The runtime used to take the first by field order; ADR-0055 §1 says
* exactly one, so it derives none.
*/
const CONTACT_SCHEMA_TWO_MASTERS = {
name: 'crm_contact',
sharingModel: 'controlled_by_parent',
fields: {
id: { name: 'id', type: 'text' },
name: { name: 'name', type: 'text' },
account: { name: 'account', type: 'master_detail', required: true, reference: 'crm_account' },
billing_account: { name: 'billing_account', type: 'master_detail', required: true, reference: 'crm_account' },
},
};
const DETAIL_SCHEMAS = {
'valid': CONTACT_SCHEMA,
'no-master-detail': CONTACT_SCHEMA_NO_MASTER_DETAIL,
'master-not-required': CONTACT_SCHEMA_MASTER_NOT_REQUIRED,
'master-readonly': CONTACT_SCHEMA_MASTER_READONLY,
'master-system': CONTACT_SCHEMA_MASTER_SYSTEM,
'master-required-lookup': CONTACT_SCHEMA_MASTER_REQUIRED_LOOKUP,
'two-masters': CONTACT_SCHEMA_TWO_MASTERS,
} as const;
type DetailVariant = keyof typeof DETAIL_SCHEMAS;
const SHARE_SCHEMA = {
name: 'sys_record_share',
isSystem: true,
fields: {
id: { name: 'id', type: 'text' },
object_name: { name: 'object_name', type: 'text' },
record_id: { name: 'record_id', type: 'text' },
recipient_type: { name: 'recipient_type', type: 'text' },
recipient_id: { name: 'recipient_id', type: 'text' },
access_level: { name: 'access_level', type: 'text' },
owner_id: { name: 'owner_id', type: 'lookup', reference: 'sys_user' },
},
};
/**
* The app's permission set: full CRUD on both objects (so requests reach the
* record layer instead of being refused by RBAC) and — deliberately — NO
* `rowLevelSecurity` anywhere. That is the shape the issue measured: the app
* expresses its record boundary entirely through OWD + sharing, and expects
* `controlled_by_parent` to follow it.
*/
const REP_SET: PermissionSet = {
name: 'crm_rep',
label: 'CRM Rep',
objects: {
crm_account: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true },
crm_contact: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true },
},
} as unknown as PermissionSet;
type Row = Record<string, unknown>;
/**
* In-memory store standing in for the engine's READ surface only — `find`,
* `findOne`, `getSchema`. It declares NO write verb: nothing under test writes
* through it, and a double that does not have a verb cannot be looser than the
* engine on that verb (the `check:engine-double-contract` family, #4434/#5480).
* Filtering runs through `matchesFilterCondition`, the same evaluator the
* security plugin itself uses, so a filter this suite asserts on is a filter
* that was really applied rather than one merely inspected.
*/
function makeStore(rows: Record<string, Row[]>, detail: DetailVariant = 'valid', faultOn?: string) {
const schemas: Record<string, unknown> = {
crm_account: ACCOUNT_SCHEMA,
crm_contact: DETAIL_SCHEMAS[detail],
sys_record_share: SHARE_SCHEMA,
};
return {
rows,
getSchema: (object: string) => schemas[object],
find: vi.fn(async (object: string, options: any = {}) => {
const all = rows[object] ?? [];
const hits = all.filter((r) => matchesFilterCondition(r, options?.where ?? null));
return typeof options?.limit === 'number' ? hits.slice(0, options.limit) : hits;
}),
findOne: vi.fn(async (object: string, options: any = {}) => {
assertEngineFindOnePredicate(object, options);
// [#7505] The one thing this double gains: a store that is DOWN for one
// object, so "the row is not there" and "I could not look" stop being the
// same observation.
if (faultOn && object === faultOn) throw datasourceOutage(object);
const all = rows[object] ?? [];
return all.find((r) => matchesFilterCondition(r, options?.where ?? null)) ?? null;
}),
};
}
/**
* [#7505] A driver outage shaped like the real one. Modelled field-for-field on
* `@objectstack/objectql`'s `DatasourceUnavailableError` — `code`, `name`,
* `datasource`, and NO `status`, because that class declares none: `rest`'s
* `mapDataError` routes it to 503 off the CODE (`rest-server.ts`, pinned by
* `rest.test.ts` "maps ERR_DATASOURCE_UNAVAILABLE → 503"). Giving the double a
* `status` the producer does not set would let these cases pass against an
* error no engine can throw.
*
* `plugin-security` does not depend on `objectql` (it is not even a
* devDependency — the plugin talks to the engine through the injected service),
* so the shape is restated here rather than imported.
*/
function datasourceOutage(object: string): Error {
const e = new Error(
`[ObjectQL] Datasource 'primary' configured for object '${object}' is declared but not connected: ` +
`its last connect attempt failed, so no driver serves it. See Setup → Datasources or the server log for the cause.`,
) as Error & { code: string; datasource: string };
e.name = 'DatasourceUnavailableError';
e.code = 'ERR_DATASOURCE_UNAVAILABLE';
e.datasource = 'primary';
return e;
}
/** The fixture rows — identical for every case; only the grant level varies. */
function fixtureRows(shareLevel: 'read' | 'edit' | null): Record<string, Row[]> {
return {
crm_account: [
{ id: 'acct_us', name: 'US Corp', owner_id: OTHER }, // shared to the rep
{ id: 'acct_eu', name: 'EU Corp', owner_id: OTHER }, // NOT shared — the excluded row
{ id: 'acct_own', name: 'Own Corp', owner_id: REP }, // the rep's own
],
crm_contact: [
{ id: 'ct_us', name: 'US contact', account: 'acct_us' },
{ id: 'ct_eu', name: 'EU contact', account: 'acct_eu' },
{ id: 'ct_own', name: 'Own contact', account: 'acct_own' },
],
sys_record_share: shareLevel
? [
{
id: 'shr_1',
object_name: 'crm_account',
record_id: 'acct_us',
recipient_type: 'user',
recipient_id: REP,
access_level: shareLevel,
},
]
: [],
};
}
interface BootOptions {
/** The single grant's level, or `null` for a fixture with no grant at all. */
shareLevel?: 'read' | 'edit' | null;
/** `'none'` boots a deployment WITHOUT plugin-sharing; `'throws'` a broken one. */
sharing?: 'real' | 'none' | 'throws';
/**
* [#7474] `'no-master-detail'` swaps the detail's schema for the AUTHORING
* DEFECT the metadata-defect leg exists to report: `controlled_by_parent`
* declared on an object with no relation to derive access from.
*
* [#8688] `'master-readonly'` / `'master-system'` swap in the
* master-reference declarations required-field validation does not cover —
* see {@link DETAIL_SCHEMAS}. [#23100] `'master-not-required'`,
* `'master-required-lookup'` and `'two-masters'` are the shapes ruling B
* stopped resolving.
*/
detail?: DetailVariant;
/** [#7474] Replace the detail rows — e.g. one whose master FK is null. */
contacts?: Row[];
/** [#7474] Replace the caller's permission set (the master-CRUD / master-RLS legs). */
sets?: PermissionSet[];
/**
* [#7505] Make `findOne` on this object throw a datasource outage, so a gate
* that probes it gets "could not read" rather than "not there".
*/
faultOn?: string;
}
async function boot(options: BootOptions = {}) {
const shareLevel = options.shareLevel === undefined ? 'edit' : options.shareLevel;
const fixture = fixtureRows(shareLevel);
if (options.contacts) fixture.crm_contact = options.contacts;
const store = makeStore(fixture, options.detail ?? 'valid', options.faultOn);
const sets = options.sets ?? [REP_SET];
let middleware: any;
const ql = {
registerMiddleware: (mw: any) => {
if (!middleware) middleware = mw;
},
getSchema: store.getSchema,
find: store.find,
findOne: store.findOne,
};
const services: Record<string, unknown> = {
manifest: { register: vi.fn() },
objectql: ql,
metadata: { get: async (n: string) => store.getSchema(n), list: async () => sets },
};
if ((options.sharing ?? 'real') === 'real') {
// The REAL sharing service over the same store — the point of the fix is
// that the derivation reuses this exact producer instead of re-deriving
// owner/share semantics inside plugin-security.
services.sharing = new SharingService({ engine: store as unknown as SharingEngine });
} else if (options.sharing === 'throws') {
services.sharing = {
buildReadFilter: async () => {
throw new Error('sharing store unreachable');
},
canEdit: async () => {
throw new Error('sharing store unreachable');
},
};
}
const ctx: any = {
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
registerService: vi.fn(),
getService: (name: string) => {
if (!(name in services)) throw new Error(`service not registered: ${name}`);
return services[name];
},
};
const plugin = new SecurityPlugin({
defaultPermissionSets: sets,
fallbackPermissionSet: 'crm_rep',
});
await plugin.init(ctx);
await plugin.start(ctx);
const repContext = () => ({ userId: REP, tenantId: 'org-1', positions: [], permissions: [] });
/**
* [ADR-0139 D6] The derivation answers the engine's `ReadableIds` leaf over
* the master, composed by the engine at its executor boundary from this
* service's own `canReadObject` / `getReadFilter` of the master. This double
* is no engine, so the composition is done for it the same way
* (`readable-ids-in-memory.testkit.ts`), with the real service — and the
* real sharing service behind it — answering the master's scope.
*/
const compose = (where: unknown, context: any) =>
composeReadableIdsInMemory(where, context, {
rows: (object) => store.rows[object],
readAdmission: (object, c) => plugin.canReadObject(object, c),
readScope: (object, c) => plugin.getReadFilter(object, c),
});
/** Run the middleware for a find of the contacts and return the `where` it injected, uncomposed. */
const injectedForContacts = async (): Promise<unknown> => {
const opCtx: any = {
object: 'crm_contact',
operation: 'find',
ast: {},
options: {},
context: repContext(),
};
await middleware(opCtx, async () => {});
return opCtx.ast.where ?? null;
};
/** The READ face: run the middleware, compose the leaf it injected, then apply the filter. */
const visibleContacts = async (): Promise<string[]> => {
const where = await compose(await injectedForContacts(), repContext());
return (store.rows.crm_contact ?? [])
.filter((r) => matchesFilterCondition(r, where as any))
.map((r) => String(r.id));
};
/**
* [#5815] The ANALYTICS read face: the scope `getReadFilter` hands the
* analytics service, which hands it to the engine (the raw-SQL strategy
* declines a scope carrying the leaf), applied to the same rows. No
* middleware runs here — this method IS the whole enforcement on that
* surface.
*/
const analyticsVisibleContacts = async (context?: any): Promise<string[]> => {
const filter = await plugin.getReadFilter('crm_contact', context ?? repContext());
const where = await compose((filter ?? null) as unknown, context ?? repContext());
return (store.rows.crm_contact ?? [])
.filter((r) => matchesFilterCondition(r, where as any))
.map((r) => String(r.id));
};
/** The WRITE face: a by-id update of one detail row. Resolves or throws. */
const updateContact = async (id: string): Promise<void> => {
const opCtx: any = {
object: 'crm_contact',
operation: 'update',
data: { id, name: 'renamed' },
options: { where: { id } },
context: repContext(),
};
await middleware(opCtx, async () => {});
};
const writableContacts = async (): Promise<string[]> => {
const out: string[] = [];
for (const row of store.rows.crm_contact ?? []) {
try {
await updateContact(String(row.id));
out.push(String(row.id));
} catch {
/* denied */
}
}
return out;
};
/**
* [#7474] The INSERT face — the one leg that reads the master FK off the body.
*
* [#8688] Resolves to whether the EXECUTOR was reached. The gate standing
* down is not the absence of a throw, it is the write continuing down the
* chain to the executor — which is where `validateRecord` runs and where the
* missing-required-field answer now comes from. A middleware that swallowed
* the operation would also "not throw", and that is a different outcome
* entirely, so the two are told apart here rather than conflated.
*/
const insertContact = async (data: Row): Promise<boolean> => {
const opCtx: any = {
object: 'crm_contact',
operation: 'insert',
data,
options: {},
context: repContext(),
};
let executorReached = false;
await middleware(opCtx, async () => {
executorReached = true;
});
return executorReached;
};
return {
store,
ctx,
plugin,
repContext,
injectedForContacts,
compose,
visibleContacts,
analyticsVisibleContacts,
updateContact,
insertContact,
writableContacts,
};
}
describe('[#5386] controlled_by_parent folds the master\'s ownership and share grants in', () => {
// ── READ face ────────────────────────────────────────────────────────────
it('READ: only children of masters the caller can actually read are visible', async () => {
const h = await boot({ shareLevel: 'edit' });
// acct_own is reachable by OWNERSHIP, acct_us by the single GRANT,
// acct_eu by neither — so its contact must not appear.
expect(await h.visibleContacts()).toEqual(['ct_us', 'ct_own']);
});
it('READ: with no grant at all, only the caller-owned master\'s children survive', async () => {
const h = await boot({ shareLevel: null });
expect(await h.visibleContacts()).toEqual(['ct_own']);
});
it('READ: the derived master id set equals what a direct find of the master returns', async () => {
const h = await boot({ shareLevel: 'edit' });
// The master half, resolved exactly as a direct read would: owner-match
// OR-ed with the caller's grants. This is the set the child filter must
// quantify over — asserted here so a future change that widens the derived
// set without widening the master's own read is caught at the seam.
const sharing = new SharingService({ engine: h.store as unknown as SharingEngine });
const masterFilter = await sharing.buildReadFilter('crm_account', {
userId: REP,
tenantId: 'org-1',
} as any);
// [ADR-0155 plan step 6] Its share arm is the share-grant leaf; the
// testkit evaluates it over the double's share rows, as a driver does.
const masterWhere = await h.compose(masterFilter, { userId: REP, tenantId: 'org-1' });
const directlyReadable = (h.store.rows.crm_account ?? [])
.filter((r) => matchesFilterCondition(r, masterWhere as any))
.map((r) => String(r.id));
expect(directlyReadable).toEqual(['acct_us', 'acct_own']);
});
// ── WRITE face ───────────────────────────────────────────────────────────
it('WRITE: a by-id update of a child under an unreachable master is denied', async () => {
const h = await boot({ shareLevel: 'edit' });
await expect(h.updateContact('ct_eu')).rejects.toThrow(/requires edit access to its master/);
});
it('WRITE: children of an owned master and of an edit-shared master stay writable', async () => {
const h = await boot({ shareLevel: 'edit' });
await expect(h.updateContact('ct_own')).resolves.toBeUndefined();
await expect(h.updateContact('ct_us')).resolves.toBeUndefined();
});
// ── the invariant the two faces owe each other ───────────────────────────
it('INVARIANT: read-visible and by-id-writable agree on the same fixture', async () => {
const h = await boot({ shareLevel: 'edit' });
const readable = await h.visibleContacts();
const writable = await h.writableContacts();
expect(readable.sort()).toEqual(writable.sort());
// …and the agreement is not the empty agreement: exactly one row is
// excluded, so "consistent" carries information.
expect(readable).not.toContain('ct_eu');
expect(readable).toHaveLength(2);
});
it('a READ-level grant opens the child for reading but NOT for writing — the master\'s own verb boundary', async () => {
const h = await boot({ shareLevel: 'read' });
// Same asymmetry a DIRECT access of the master has: a `read` share widens
// rows for reads only; `canEdit` refuses it. The derived faces must track
// that per-verb answer rather than collapsing to one of them.
expect(await h.visibleContacts()).toEqual(['ct_us', 'ct_own']);
expect(await h.writableContacts()).toEqual(['ct_own']);
await expect(h.updateContact('ct_us')).rejects.toThrow(/record sharing/);
});
// ── boundary conditions ──────────────────────────────────────────────────
it('the derivation does NO store work; the master\'s share arm is answered inside the composition, and the detail is never re-entered', async () => {
const h = await boot({ shareLevel: 'edit' });
h.store.find.mockClear();
// [ADR-0139 D6] The middleware writes the leaf and walks the chain over
// the registry: no pre-scan of the master, no read of anything.
const injected = await h.injectedForContacts();
const during = h.store.find.mock.calls.map((c: any[]) => String(c[0]));
expect(during).not.toContain('crm_account');
expect(during).not.toContain('crm_contact');
// The master's scope is composed by the engine (here, by the testkit),
// and the detail itself is never read to answer its own scope.
// [ADR-0155 plan step 6] The master's share arm is the share-grant leaf,
// evaluated inside the composed statement: no grant row is read on its
// own. `acct_us`, which the rep reaches only through its grant, in the
// composed set is the direct evidence the sharing half ran inside the
// composition and not merely that some filter came back.
const composed = await h.compose(injected, h.repContext());
const reads = h.store.find.mock.calls.map((c: any[]) => String(c[0]));
expect(reads).not.toContain('sys_record_share');
expect(reads).not.toContain('crm_account');
expect(reads).not.toContain('crm_contact');
expect(JSON.stringify(composed)).toContain('acct_us');
});
it('a deployment WITHOUT plugin-sharing is unchanged — RLS-only derivation, nothing to fold', async () => {
// No sharing service means no owner scope and no grants anywhere in the
// deployment, so a direct find of the master returns every row too: the
// derived set stays point-for-point equal to it.
const h = await boot({ shareLevel: 'edit', sharing: 'none' });
expect(await h.visibleContacts()).toEqual(['ct_us', 'ct_eu', 'ct_own']);
await expect(h.updateContact('ct_eu')).resolves.toBeUndefined();
});
it('fail-closed: a sharing service that throws denies BOTH faces', async () => {
const h = await boot({ shareLevel: 'edit', sharing: 'throws' });
expect(await h.visibleContacts()).toEqual([]);
await expect(h.updateContact('ct_us')).rejects.toThrow(/record sharing/);
});
});
// ---------------------------------------------------------------------------
/**
* [#5815] The THIRD face of the same contract — `getReadFilter`, the read-scope
* provider bound by the analytics / raw-SQL path.
*
* The suite above pins the engine middleware and the by-id write gate against
* one fixture precisely so a third, quieter answer cannot hide between them.
* There WAS one: `getReadFilter` composed the RLS layer and the sharing layer
* and never called the controlled_by_parent derivation at all. On this exact
* fixture both of those layers legitimately return `null` — the app authors no
* RLS, and plugin-sharing maps `controlled_by_parent` to `public` — so the
* composed scope came back `undefined`: NO predicate. A caller who could not
* read `acct_eu` could still `COUNT(*)` and `GROUP BY` its contacts.
*
* These cases therefore assert AGREEMENT, not a filter shape. The two read
* surfaces may compose their layers in any order and produce different ASTs;
* what they may never do is disagree about which rows are visible.
*/
describe('[#5815] getReadFilter enforces the same read scope as the engine middleware', () => {
it('PARITY: the analytics read scope and the middleware-injected `ast.where` see the same rows', async () => {
const h = await boot({ shareLevel: 'edit' });
const viaMiddleware = await h.visibleContacts();
const viaReadFilter = await h.analyticsVisibleContacts();
expect(viaReadFilter.sort()).toEqual(viaMiddleware.sort());
// …and the agreement carries information: one row is excluded on BOTH
// surfaces. Without this, "identical" would be satisfied by two surfaces
// that each return everything — which is exactly the broken state.
expect(viaReadFilter).not.toContain('ct_eu');
expect(viaReadFilter).toHaveLength(2);
});
it('the returned scope is a real predicate, not `undefined` — the defect measured', async () => {
const h = await boot({ shareLevel: 'edit' });
const filter = await h.plugin.getReadFilter('crm_contact', h.repContext());
// Before the fix this was `undefined` (RLS null AND sharing null), which
// the raw-SQL path spreads into a WHERE that constrains nothing. The
// predicate is the engine's leaf over the master (ADR-0139 D6): it names
// the master and binds no master id, and composed it admits exactly the
// contacts under the accounts the caller may read.
expect(filter).toBeDefined();
expect(JSON.stringify(filter)).toContain('"object":"crm_account"');
expect(JSON.stringify(filter)).not.toMatch(/acct_own|acct_eu|acct_us/);
const composed = await h.compose(filter, h.repContext());
expect(JSON.stringify(composed)).toContain('acct_own');
expect(JSON.stringify(composed)).not.toContain('acct_eu');
});
it('PARITY with no grant at all: both surfaces narrow to the caller-owned master', async () => {
const h = await boot({ shareLevel: null });
expect(await h.analyticsVisibleContacts()).toEqual(await h.visibleContacts());
expect(await h.analyticsVisibleContacts()).toEqual(['ct_own']);
});
it('PARITY on a READ-level grant: the read share widens the analytics face too', async () => {
const h = await boot({ shareLevel: 'read' });
expect(await h.analyticsVisibleContacts()).toEqual(['ct_us', 'ct_own']);
expect(await h.analyticsVisibleContacts()).toEqual(await h.visibleContacts());
});
it('PARITY without plugin-sharing: neither surface narrows, for the same reason', async () => {
// Both faces stand down together — there is no owner scope and there are no
// grants anywhere in the deployment, so a direct find of the master returns
// every row. Parity must hold in the WIDE direction as well, or the pin
// would merely be asserting that the analytics face is always narrower.
const h = await boot({ shareLevel: 'edit', sharing: 'none' });
expect(await h.analyticsVisibleContacts()).toEqual(['ct_us', 'ct_eu', 'ct_own']);
expect(await h.analyticsVisibleContacts()).toEqual(await h.visibleContacts());
});
it('fail-closed: a sharing service that throws denies the analytics face too', async () => {
const h = await boot({ shareLevel: 'edit', sharing: 'throws' });
expect(await h.analyticsVisibleContacts()).toEqual([]);
expect(await h.analyticsVisibleContacts()).toEqual(await h.visibleContacts());
});
it('getReadFilter does NO store work for the derivation: the master is read only when the engine composes the leaf', async () => {
const h = await boot({ shareLevel: 'edit' });
h.store.find.mockClear();
const filter = await h.plugin.getReadFilter('crm_contact', h.repContext());
// [ADR-0139 D6] `getReadFilter(contact)` resolves the contact's OWN
// sharing half (the grant table) and writes the leaf for the master; it
// pre-scans no master and never re-enters the detail.
const before = h.store.find.mock.calls.map((c: any[]) => String(c[0]));
expect(before).not.toContain('crm_account');
expect(before).not.toContain('crm_contact');
// Composing the leaf asks `getReadFilter(account)`, whose sharing half
// carries the share-grant leaf (ADR-0155 plan step 6), evaluated inside
// the composed statement: `acct_us`, reached only through its grant, in
// the composed set is direct evidence the derivation runs on THIS path
// rather than a filter merely coming back from somewhere.
h.store.find.mockClear();
const composed = await h.compose(filter ?? null, h.repContext());
const reads = h.store.find.mock.calls.map((c: any[]) => String(c[0]));
expect(reads).not.toContain('sys_record_share');
expect(reads).not.toContain('crm_contact');
expect(JSON.stringify(composed)).toContain('acct_us');
});
it('a delegated (on-behalf-of) read whose delegator does not exist still denies outright — unchanged by the added layer', async () => {
// [ADR-0090 D10] getReadFilter composes the delegator intersection for a
// delegated context (ADR-0139 D5.1 as amended). This fixture stores no
// `sys_user` row, so the link names a delegator who does not exist and the
// read fails closed BEFORE any layer is composed. Pinned here because the
// added layer must not become a reason to compute a scope for a context
// whose delegator cannot be resolved.
const h = await boot({ shareLevel: 'edit' });
const delegated = { ...h.repContext(), onBehalfOf: { userId: OTHER } };
expect(await h.analyticsVisibleContacts(delegated)).toEqual([]);
});
});
// ---------------------------------------------------------------------------
/**
* [#7474] SIX conditions refuse a write in `assertControlledByParentWrite`, and
* until the maintainer ruling of 2026-08-11 they answered with ONE sentence and
* ONE code: `403 PERMISSION_DENIED — requires edit access to its master record`.
*
* Three of them are genuine authorization verdicts and keep exactly that. Three
* are not verdicts at all — a broken `master_detail` declaration, a row that
* does not exist, a null master FK — and the shared sentence was a false
* statement with a false remedy: "ask whoever owns the parent record" cannot
* fix any of them. Worse for the app author, the metadata defect is a precisely
* detectable AUTHORING error that was wearing the costume of routine RBAC
* noise, which is the class of thing nobody ever investigates.
*
* ## Why these cases assert `code` and `status`, never just a throw
*
* The defect is the ENVELOPE, not the refusal: every one of these six threw
* before this change too. A `rejects.toThrow()` — or a message-only assertion —
* carries one bit where the defect has two, so it stays green on precisely the
* behaviour the issue reported. The minimum here is therefore the ADR-0112 pair
* (`code` + `status`), plus the message where the WORDING is the contract: the
* three authorization legs must keep their sentence verbatim, because that
* sentence is what a user reads and what consumers already pin.
*
* The pinned pairs are the split itself:
*
* | leg | status | code |
* |----------------------------------------|--------|-------------------------|
* | no object-level `update` on the master | 403 | PERMISSION_DENIED |
* | master row outside the write RLS | 403 | PERMISSION_DENIED |
* | no `edit`-level share grant | 403 | PERMISSION_DENIED |
* | controlled_by_parent, no master_detail | 422 | INVALID_METADATA |
* | target record not found | 404 | RECORD_NOT_FOUND |
* | detail has no master reference | 422 | MISSING_REQUIRED_FIELD |
*
* [#8688] The last row has since NARROWED — the maintainer ruling of
* 2026-08-15 supersedes #7474's envelope choice for one of its two shapes. An
* INSERT that omits the FK is handed to required-field validation (`400
* VALIDATION_FAILED` with `fields[]`) wherever validation provably refuses it;
* the row above still holds for the stored-row shape. [#25095] Of the three
* declarations validation does not cover, the two flagged ones now answer an
* insert `422 INVALID_METADATA` instead (the third resolves no relation). The insert leg below was rewritten
* for that ruling, not adjusted to match observed behaviour — the successor
* asserts both sides of the condition.
*/
describe('[#7474] the six refusal legs answer with six envelopes, not one', () => {
/** The thrown error itself — `rejects.toThrow` cannot see `code` / `status`. */
const refusalOf = async (run: Promise<unknown>): Promise<any> => {
try {
await run;
} catch (e) {
return e;
}
throw new Error('expected the write to be refused, but it resolved');
};
/** REP_SET with the master's object-level `update` withheld. */
const NO_MASTER_EDIT: PermissionSet = {
name: 'crm_rep',
label: 'CRM Rep',
objects: {
crm_account: { allowRead: true, allowCreate: true, allowEdit: false, allowDelete: true },
crm_contact: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true },
},
} as unknown as PermissionSet;
/** REP_SET plus a write RLS on the MASTER that matches no row in the fixture. */
const MASTER_WRITE_RLS: PermissionSet = {
name: 'crm_rep',
label: 'CRM Rep',
objects: {
crm_account: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true },
crm_contact: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true },
},
rowLevelSecurity: [
{ object: 'crm_account', operation: 'update', using: "name = 'No Such Corp'" },
],
} as unknown as PermissionSet;
// ── the three GENUINE authorization verdicts — unchanged, verbatim ────────
it('403 PERMISSION_DENIED: the caller holds no object-level update on the master', async () => {
const h = await boot({ shareLevel: 'edit', sets: [NO_MASTER_EDIT] });
const err = await refusalOf(h.updateContact('ct_own'));
expect(err.code).toBe('PERMISSION_DENIED');
expect(err.statusCode).toBe(403);
// The sentence is contract on this leg — a user reads it, and consumers
// pin it. It must survive the split byte-for-byte.
expect(err.message).toContain("requires edit access to its master record");
expect(err.message).toContain("no edit permission on master 'crm_account'");
});
it('403 PERMISSION_DENIED: the master row is outside the caller\'s write RLS', async () => {
const h = await boot({ shareLevel: 'edit', sets: [MASTER_WRITE_RLS] });
const err = await refusalOf(h.updateContact('ct_own'));
expect(err.code).toBe('PERMISSION_DENIED');
expect(err.statusCode).toBe(403);
expect(err.message).toContain('requires edit access to its master record');
expect(err.message).toContain('row-level security');
});
it('403 PERMISSION_DENIED: the master carries no edit-level share grant', async () => {
const h = await boot({ shareLevel: 'read' });
const err = await refusalOf(h.updateContact('ct_us'));
expect(err.code).toBe('PERMISSION_DENIED');
expect(err.statusCode).toBe(403);
expect(err.message).toContain('requires edit access to its master record');
expect(err.message).toContain('record sharing');
});
// ── the three NON-VERDICT legs — split by true semantics ──────────────────
it('422 INVALID_METADATA: controlled_by_parent declared with no master_detail relation', async () => {
const h = await boot({ shareLevel: 'edit', detail: 'no-master-detail' });
const err = await refusalOf(h.updateContact('ct_own'));
expect(err.code).toBe('INVALID_METADATA');
expect(err.status).toBe(422);
expect(err.statusCode).toBe(422);
// The remedy has to be IN the message: `details` is not a carrier the
// client can rely on (#7450), so the sentence is the whole fix-it.
// [#23100] Reworded with the rule: "no relation" is now "not exactly one
// required master_detail" (ADR-0055 §1), and the remedy says so.
expect(err.message).toContain('not exactly one required master_detail field');
expect(err.message).toContain('Declare one master_detail field with required: true');
// …and it must NOT wear the 403's costume: that prefix is a MATCHER at both
// transports, so borrowing it would re-flatten this to PERMISSION_DENIED.
expect(err.message).not.toContain('[Security] Access denied');
expect(err.message).not.toContain('requires edit access to its master record');
});
it('404 RECORD_NOT_FOUND: the by-id write targets a detail row that does not exist', async () => {
const h = await boot({ shareLevel: 'edit' });
const err = await refusalOf(h.updateContact('ct_deleted_concurrently'));
expect(err.code).toBe('RECORD_NOT_FOUND');
expect(err.status).toBe(404);
// [#21771] The addressed by-id write now asks the read door first, so a
// missing id gets the READ door's own not-found producer — which spells
// the status once — rather than the master gate's detail copy.
expect(err.message).toBe(recordNotFoundError('crm_contact', 'ct_deleted_concurrently').message);
expect(err.message).toContain('ct_deleted_concurrently');
expect(err.message).not.toContain('requires edit access to its master record');
});
it('404 is real absence, not an RLS-hidden row: the probe reads under a SYSTEM context', async () => {
// The one thing a 404 must never become is an oracle. `ct_eu` exists but
// its master is unreachable to the caller — the row is read as system, so
// it is FOUND here and falls through to the authorization leg. Both halves
// asserted together: this is what makes the 404 above mean "absent".
const h = await boot({ shareLevel: 'edit' });
const hidden = await refusalOf(h.updateContact('ct_eu'));
expect(hidden.code).toBe('PERMISSION_DENIED');
expect(hidden.statusCode).toBe(403);
expect(hidden.message).toContain('requires edit access to its master record');
});
it('422 MISSING_REQUIRED_FIELD: the stored detail row has no master reference', async () => {
const h = await boot({
shareLevel: 'edit',
contacts: [{ id: 'ct_orphan', name: 'Orphan contact', account: null }],
});
const err = await refusalOf(h.updateContact('ct_orphan'));
expect(err.code).toBe('MISSING_REQUIRED_FIELD');
expect(err.status).toBe(422);
expect(err.statusCode).toBe(422);
// The stored-row wording names the row, because the caller cannot fix this
// one by sending a different payload.
expect(err.message).toContain("record 'ct_orphan' has no value in 'account'");
expect(err.message).not.toContain('requires edit access to its master record');
});
/**
* [#8688] THE PIN THAT MOVED, rewritten deliberately.
*
* Until the maintainer ruling of 2026-08-15 this leg read:
*
* it('422 MISSING_REQUIRED_FIELD: an insert that omits the master reference')
* expect(err.code).toBe('MISSING_REQUIRED_FIELD');
* expect(err.status).toBe(422);
* expect(err.message).toContain("did not supply 'account'");
*
* That assertion was correct about the code and wrong about who should be
* answering. The gate runs in the middleware chain OUTSIDE the executor that
* calls `validateRecord`, so on an insert it short-circuited required-field
* validation on the one field they share — and the same omission that every
* other required field answers `400 VALIDATION_FAILED` with `fields[]` came
* back `422 MISSING_REQUIRED_FIELD` with no `fields[]` and a `[Security]`
* prefix. Measured live on 17.0.0 GA, on the very same field whose
* present-but-unresolvable case already answers the wanted envelope.
*
* The ruling supersedes #7474's envelope choice on that ruling's own
* rationale: if a detail without its master is "precisely a required value
* that is absent", the platform's contract for that is the validation
* envelope. `fields[]` cannot be added while keeping the old code — BOTH
* transport doors emit `fields[]` only for the `VALIDATION_FAILED` duck-type
* and each overwrites `code` when it matches (`mapDataError`,
* `packages/rest/src/rest-server.ts`; `validationFailureDetails` /
* `VALIDATION_FAILED_STATUS = 400`, `packages/types/src/validation-failure.ts`)
* — so the pin had to move for the defect to be fixable at all.
*
* ⛔ The successor is NOT "the gate no longer refuses". The stand-down is
* CONDITIONAL, and the three cases below it are the condition: they are the
* shapes where nothing downstream would refuse, and the gate must still.
*/
it('[#8688] a REQUIRED master_detail omitted on insert is validation\'s answer, not the gate\'s', async () => {
const h = await boot({ shareLevel: 'edit' });
const payload = { name: 'New contact' };
// ── half 1: the gate stands down, and the write CONTINUES ───────────────
// Not merely "it did not throw": the executor is where `validateRecord`
// runs, so reaching it is the whole content of the hand-over. A middleware
// that silently swallowed the operation would also not throw.
await expect(h.insertContact(payload)).resolves.toBe(true);
// ── half 2: …and the subsystem it handed to really does refuse ──────────
// The REAL `validateRecord` (aliased to `packages/objectql/src` by this
// package's vitest config, so this is a verdict about the source in the
// checkout, never a prebuilt dist), on the same payload and the same
// schema. Without this half, half 1 would be indistinguishable from
// silently admitting an orphan row.
let err: any;
try {
validateRecord(CONTACT_SCHEMA as any, payload, 'insert');
} catch (e) {
err = e;
}
// The ADR-0112 envelope. `ValidationError` declares no `status` of its own:
// 400 is the transports' constant for exactly this duck-type, and BOTH
// properties the two doors branch on are asserted here rather than the
// status they derive from them.
expect(err?.name).toBe('ValidationError');
expect(err?.code).toBe('VALIDATION_FAILED');
// …and the half the card is actually about — a form can now highlight the
// offending input, which no `MISSING_REQUIRED_FIELD` body ever carried.
expect(err.fields).toContainEqual(
expect.objectContaining({ field: 'account', code: 'required' }),
);
});
/**
* [#8688] The shapes the stand-down deliberately does NOT cover.
*
* `validateRecord` skips provenance-flagged fields before the required check
* (`if (def.system || def.readonly) continue;`) and never fires on a field
* that is not `required`. Handing those over would mint a detail row with a
* null master FK — unmatchable by the `controlled_by_parent` read filter
* (`fk IN (readable masters)`), so readable by nobody, and answering 422 on
* every later by-id write. Each case asserts BOTH halves: the gate still
* refuses, AND the real validator raises nothing, which is why it must.
*
* [#25095] The gate's answer for the two flagged shapes moved: the parse
* refuses the declaration (`master-not-writable`), and the gate refuses every
* insert under it as that defect, `422 INVALID_METADATA` with the parse's own
* message, before the empty-master branch is reached.
*/
it.each([
['`required` + `readonly`', 'master-readonly' as const, CONTACT_SCHEMA_MASTER_READONLY],
['`required` + `system`', 'master-system' as const, CONTACT_SCHEMA_MASTER_SYSTEM],
])('[#8688 → #25095] the gate still refuses an insert omitting the master: %s', async (_label, detail, schema) => {
const payload = { name: 'New contact' };
// Validation does not cover this shape — nothing downstream would refuse.