Repository navigation
Expand file tree
/
Copy pathsecurity-plugin.test.ts
More file actions
4616 lines (4293 loc) · 232 KB
/
Copy pathsecurity-plugin.test.ts
File metadata and controls
4616 lines (4293 loc) · 232 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, vi } from 'vitest';
import { assertEngineUpdateDispatch, assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core';
import { recordNotFoundError } from '@objectstack/core';
import { SecurityPlugin } from './security-plugin.js';
import { PermissionEvaluator, crudBucketForOperation } from './permission-evaluator.js';
import { FieldMasker } from './field-masker.js';
import { RLSCompiler, RLS_DENY_FILTER } from './rls-compiler.js';
// #4983 — `isSupportedRlsExpression` now lives in @objectstack/formula, and its
// SHAPE unit tests moved with it (`formula/src/rls-predicate.test.ts`). What
// stays here is the consumer-side half: that this compiler's drop / warn /
// fail-closed behaviour really is what that predicate describes.
import { isSupportedRlsExpression } from '@objectstack/formula';
import type { PermissionSet } from '@objectstack/spec/security';
import { RLS } from '@objectstack/spec/security';
import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system';
/**
* The registry answer for the doubles below that fire every `kernel:ready`
* handler, as the kernel does: the plugin refuses a boot whose registry lacks
* the identity objects its authorization store reads, so a double that boots it
* holds those two names and nothing else (`authz-identity-objects-boot-refusal.test.ts`).
*/
const identityObjectsOnly = (name: string) =>
name === 'sys_user' || name === 'sys_member' ? { name, fields: {} } : undefined;
/**
* [commit a016f08b8] What the ENGINE does inside the middleware's `next()` — the part of
* `ObjectQL.insert` the doubles in this file stand in for.
*
* Since commit a016f08b8 the insert-side RLS `check` is not evaluated in the middleware:
* it is INSTALLED on the operation context and run by the engine once the
* `beforeInsert` chain has produced the row that will be stored. A double whose
* executor is a bare `async () => {}` therefore models an engine that carries a
* write past a gate that never ran — and the middleware refuses exactly that,
* fail-closed, rather than vouching for it. A looser double would convert a
* green suite into no suite at all, which is the family `check:engine-double-contract`
* exists for.
*
* So the executor honours the seam the way the engine does: the flag first (it
* answers "did the seam run", never "did the write pass"), then the judgement.
* These doubles run no hooks, so the rows an insert would store ARE
* `opCtx.data` — each element of an array insert ([#19964]).
*
* [#19950] A predicate (`multi`) update installs the same seam, and the engine
* hands it every row the composed AST matches, merged with the payload. These
* doubles hold no table, so that match set is empty: the judgement runs over
* no rows, exactly as a real engine's would over an empty one.
*
* [#19989] A by-id update installs it too, and a real engine hands it the one
* row it writes, merged with the final payload. These doubles hold no row to
* merge onto, so that judgement also runs over none here: the cells in this
* file exercise the middleware's own change-set judgement, which still runs,
* and the stored-row judgement is pinned against the real engine in
* `rls-check-by-id-update-post-hook.test.ts`.
*/
const runEngineWriteBody = async (opCtx: any): Promise<void> => {
const seam = opCtx?.postHookWriteImageCheck;
if (!seam) return;
seam.honoured = true;
if (opCtx.operation === 'update') {
await seam.evaluate([]);
return;
}
await seam.evaluate(Array.isArray(opCtx.data) ? opCtx.data : [opCtx.data]);
};
// ---------------------------------------------------------------------------
// SecurityPlugin – basic metadata
// ---------------------------------------------------------------------------
describe('SecurityPlugin', () => {
it('should have correct metadata', () => {
const plugin = new SecurityPlugin();
expect(plugin.name).toBe('com.objectstack.security');
expect(plugin.type).toBe('standard');
expect(plugin.version).toBe('1.0.0');
expect(plugin.dependencies).toContain('com.objectstack.engine.objectql');
});
it('should register services during init', async () => {
const plugin = new SecurityPlugin();
const manifestService = { register: vi.fn() };
const ctx: any = {
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
registerService: vi.fn(),
getService: vi.fn().mockImplementation((name: string) => {
if (name === 'manifest') return manifestService;
return undefined;
}),
};
await plugin.init(ctx);
expect(ctx.registerService).toHaveBeenCalledWith('security.permissions', expect.any(PermissionEvaluator));
expect(ctx.registerService).toHaveBeenCalledWith('security.rls', expect.any(RLSCompiler));
expect(ctx.registerService).toHaveBeenCalledWith('security.fieldMasker', expect.any(FieldMasker));
expect(manifestService.register).toHaveBeenCalled();
});
it('should warn and return when objectql service is missing', async () => {
const plugin = new SecurityPlugin();
const manifestService = { register: vi.fn() };
const ctx: any = {
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
registerService: vi.fn(),
getService: vi.fn().mockImplementation((name: string) => {
if (name === 'manifest') return manifestService;
throw new Error('not found');
}),
};
await plugin.init(ctx);
await plugin.start(ctx);
expect(ctx.logger.warn).toHaveBeenCalled();
});
it('should warn when objectql does not support middleware', async () => {
const plugin = new SecurityPlugin();
const manifestService = { register: vi.fn() };
const ctx: any = {
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
registerService: vi.fn(),
getService: vi.fn().mockImplementation((name: string) => {
if (name === 'manifest') return manifestService;
return {}; // objectql without registerMiddleware
}),
};
await plugin.init(ctx);
await plugin.start(ctx);
expect(ctx.logger.warn).toHaveBeenCalled();
});
it('should register middleware when objectql supports it', async () => {
const plugin = new SecurityPlugin();
const registerMiddleware = vi.fn();
const manifestService = { register: vi.fn() };
const ctx: any = {
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
registerService: vi.fn(),
getService: vi.fn().mockImplementation((name: string) => {
if (name === 'manifest') return manifestService;
return { registerMiddleware };
}),
};
await plugin.init(ctx);
await plugin.start(ctx);
expect(registerMiddleware).toHaveBeenCalledWith(expect.any(Function));
});
it('should destroy without error', async () => {
const plugin = new SecurityPlugin();
await expect(plugin.destroy()).resolves.toBeUndefined();
});
// -------------------------------------------------------------------------
// Bootstrap-replay wiring — the middleware registered in start() re-runs
// the bootstrap for exactly the writes `shouldReplayBootstrapFor` admits.
// The predicate itself is pinned exhaustively next to its producer
// (bootstrap-platform-admin-walled-owner.test.ts); THIS pin is that the
// middleware actually consults it. [#11974 / #11663 L4] The trigger set is
// NARROWED: commit c0714eb5d's update arm (email_verified / email) retired with the
// walled elevation it existed to re-attempt — under `single` (this suite's
// posture) only a sys_user insert/create can change the promotion answer.
// -------------------------------------------------------------------------
it('re-runs the bootstrap on a sys_user insert, and no longer on the verifying update (#11974 narrowed #11343)', async () => {
const plugin = new SecurityPlugin();
const middlewares: any[] = [];
const manifestService = { register: vi.fn() };
// A ql fake rich enough for runBootstrap to COMPLETE (that is what arms
// the replay: `bootstrapRanOnce` is only set on completion, right before
// the 'platform bootstrap complete' log this pin counts).
const ql: any = {
registerMiddleware: (mw: any) => middlewares.push(mw),
find: vi.fn(async () => []),
findOne: vi.fn(async (object: string, query?: EngineFindOneQueryInput) => { assertEngineFindOnePredicate(object, query); return null; }),
insert: vi.fn(async (_o: string, d: any) => ({ id: d?.id ?? 'x' })),
// Opens with the PRODUCER's own dispatch predicate, never a hand-mirrored
// guard (check:engine-double-contract) — same shape as the makeQl double
// in bootstrap-platform-admin-walled-owner.test.ts.
update: vi.fn(async (_o: string, d: any, o?: any) => {
assertEngineUpdateDispatch(d, o);
return true;
}),
getSchema: identityObjectsOnly,
};
const metadata = { get: async () => null, list: async () => [] };
const services: Record<string, any> = { manifest: manifestService, objectql: ql, metadata };
const hook = vi.fn();
const ctx: any = {
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
registerService: vi.fn(),
getService: (name: string) => {
if (!(name in services)) throw new Error(`service not registered: ${name}`);
return services[name];
},
hook,
};
await plugin.init(ctx);
await plugin.start(ctx);
// Drive the initial bootstrap to completion by firing every kernel:ready
// callback in registration order — exactly what the kernel does. start()
// registers several (runBootstrap is not the first), so firing only one
// would leave the replay disarmed and every assertion below vacuous.
const ready = hook.mock.calls.filter((c: any[]) => c[0] === 'kernel:ready');
expect(ready.length).toBeGreaterThan(0);
for (const [, cb] of ready) await cb();
const completions = () =>
ctx.logger.info.mock.calls.filter((c: any[]) => String(c[0]).includes('platform bootstrap complete')).length;
// Positive control: the initial run completed — the replay is armed. If
// this line fails, the fake ql was not rich enough and every assertion
// below would be vacuous.
expect(completions()).toBe(1);
const drive = async (opCtx: any) => {
for (const mw of middlewares) {
try {
await mw(opCtx, () => runEngineWriteBody(opCtx));
} catch {
// Another middleware (e.g. the CRUD-authorization one) may refuse a
// bare opCtx — irrelevant here: the replay middleware never throws.
}
}
};
// The formerly-verifying write (better-auth flips emailVerified on link
// click) ⇒ NO re-run any more: the walled elevation it re-attempted is
// retired, and `single` never read this column.
await drive({ object: 'sys_user', operation: 'update', data: { id: 'u1', email_verified: true } });
expect(completions()).toBe(1);
// An unrelated profile edit ⇒ NO re-run (unchanged).
await drive({ object: 'sys_user', operation: 'update', data: { id: 'u1', name: 'New Name' } });
expect(completions()).toBe(1);
// The original insert trigger still fires — the over-denial control: the
// narrowing must not retire `single`'s first-user promotion path.
await drive({ object: 'sys_user', operation: 'insert', data: { email: 'a@b.c' } });
expect(completions()).toBe(2);
});
// [ADR-0105 D2 / #3623] start() hands the engine a posture accessor so the
// driver-level native tenant scope can widen to the membership union under
// `group`. Wired from the enforcement layer on purpose: no SecurityPlugin,
// no widening.
it('wires the tenancy-posture provider onto the engine, reporting the LIVE cached posture', async () => {
const plugin = new SecurityPlugin();
const registerMiddleware = vi.fn();
const setTenancyPostureProvider = vi.fn();
const manifestService = { register: vi.fn() };
const ctx: any = {
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
registerService: vi.fn(),
getService: vi.fn().mockImplementation((name: string) => {
if (name === 'manifest') return manifestService;
if (name === 'tenancy') return { posture: 'group' };
return { registerMiddleware, setTenancyPostureProvider };
}),
};
await plugin.init(ctx);
await plugin.start(ctx);
expect(setTenancyPostureProvider).toHaveBeenCalledWith(expect.any(Function));
const provider = setTenancyPostureProvider.mock.calls[0][0] as () => string;
expect(provider()).toBe('group');
});
it('an engine without the provider seam is tolerated (older engine)', async () => {
const plugin = new SecurityPlugin();
const registerMiddleware = vi.fn();
const manifestService = { register: vi.fn() };
const ctx: any = {
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
registerService: vi.fn(),
getService: vi.fn().mockImplementation((name: string) => {
if (name === 'manifest') return manifestService;
if (name === 'tenancy') return { posture: 'group' };
return { registerMiddleware };
}),
};
await plugin.init(ctx);
await expect(plugin.start(ctx)).resolves.toBeUndefined();
});
// -------------------------------------------------------------------------
// org-scoping probe — when @objectstack/plugin-org-scoping is installed
// (i.e. the `org-scoping` service is registered), SecurityPlugin keeps
// wildcard `current_user.organization_id` RLS policies. Otherwise it
// strips them so single-tenant deployments aren't filtered to nothing.
// -------------------------------------------------------------------------
const makeMiddlewareCtx = (overrides: { permissionSets: PermissionSet[]; objectFields?: string[]; schemaExtra?: Record<string, any>; orgScoping?: boolean; findOneImpl?: (query: any) => any; sharing?: any }) => {
const fields: Record<string, any> = {};
for (const f of overrides.objectFields ?? ['id', 'organization_id', 'owner_id', 'name']) {
fields[f] = { name: f };
}
const baseSchema: any = { name: 'task', fields, ...(overrides.schemaExtra ?? {}) };
let middleware: any;
// The pre-image write-authorization check re-reads the target row via
// `ql.findOne(object, { where: { $and: [{ id }, writeFilter] }, … })`.
// `findOneImpl` lets a test decide whether that row is "visible" (owned /
// in-tenant) or filtered out (someone else's row → null → deny).
// [#21829] With `find` beside it this is an engine double, so its `findOne`
// refuses what the real engine refuses (`check:engine-double-contract`).
const findOne = vi.fn(async (object: string, query: any) => {
assertEngineFindOnePredicate(object, query as EngineFindOneQueryInput);
return overrides.findOneImpl ? overrides.findOneImpl(query) : null;
});
// [#21829] A predicate update or delete asks the read door which matched
// rows the caller can read, and a `ql` that cannot answer refuses the
// write. This double holds no rows, so the read answers none.
const find = vi.fn(async (_object: string, _query: any) => [] as Record<string, unknown>[]);
const ql = {
registerMiddleware: (mw: any) => {
// Capture only the FIRST middleware (the security CRUD one);
// ignore the secondary bootstrap-replay middleware registered
// later in `start()`.
if (!middleware) middleware = mw;
},
getSchema: () => baseSchema,
findOne,
find,
};
const metadata = {
get: async () => baseSchema,
list: async () => overrides.permissionSets,
};
const services: Record<string, any> = {
manifest: { register: vi.fn() },
objectql: ql,
metadata,
};
if (overrides.orgScoping) {
// Sentinel object — SecurityPlugin only checks truthiness.
services['org-scoping'] = { name: 'com.objectstack.org-scoping' };
}
// [#4467] The optional plugin-sharing service. Absent by default, which is
// exactly the deployment shape every case above assumes; supply it to
// exercise the OWD/sharing half of the read scope.
if (overrides.sharing) services['sharing'] = overrides.sharing;
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];
},
};
return {
ctx,
findOne,
run: async (opCtx: any) => {
await middleware(opCtx, () => runEngineWriteBody(opCtx));
return opCtx;
},
};
};
const tenantPolicySet: PermissionSet = {
name: 'member_default',
label: 'Member',
objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } },
rowLevelSecurity: [
{ name: 'tenant_isolation', object: '*', operation: 'all', using: 'organization_id = current_user.organization_id' },
],
} as any;
// Note: `organization_id` auto-injection lives in `@objectstack/plugin-org-scoping`
// and is covered by that package's tests. SecurityPlugin only owns
// `owner_id` auto-stamping.
it('owner_id is always auto-injected on insert (regardless of org-scoping)', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({ permissionSets: [tenantPolicySet] });
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
// The row carries the caller's own organization, as the org-scoping
// auto-stamp writes it in `beforeInsert` ahead of the post-image check. The
// `tenant_isolation` policy declares no `check`, so its `using` is the
// insert check (ADR-0058 D4 default) and a row with no organization would
// be refused. This double runs no hooks, so the payload stands in for them.
const opCtx: any = {
object: 'task', operation: 'insert', data: { name: 'A', organization_id: 'org-1' },
context: { userId: 'u1', tenantId: 'org-1', positions: [], permissions: [] },
};
await harness.run(opCtx);
// SecurityPlugin does not touch organization_id — that's plugin-org-scoping's
// job — so the value arrives exactly as sent.
expect(opCtx.data.organization_id).toBe('org-1');
expect(opCtx.data.owner_id).toBe('u1');
});
// -------------------------------------------------------------------------
// [#3004] `owner_id` anchor guard — the ownership anchor is system-managed
// for non-privileged writers: forging it on insert or transferring it on
// update requires the transfer grant (allowTransfer / modifyAllRecords).
// -------------------------------------------------------------------------
describe('owner_id anchor guard (#3004)', () => {
const memberSet: PermissionSet = {
name: 'member_default',
label: 'Member',
objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } },
} as any;
const transferSet: PermissionSet = {
name: 'can_transfer',
label: 'Transfer',
objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowTransfer: true } },
} as any;
const modifyAllSet: PermissionSet = {
name: 'org_admin_like',
label: 'Admin',
objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, modifyAllRecords: true } },
} as any;
const boot = async (sets: PermissionSet[], findOneImpl?: (query: any) => any) => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({ permissionSets: sets, findOneImpl });
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
return harness;
};
const memberCtx = (extra: Record<string, unknown> = {}) =>
({ userId: 'u1', tenantId: 'org-1', positions: [], permissions: [], ...extra });
it('insert forging another user as owner is denied for a plain member', async () => {
const harness = await boot([memberSet]);
const opCtx: any = {
object: 'task', operation: 'insert', data: { name: 'A', owner_id: 'victim' },
context: memberCtx(),
};
await expect(harness.run(opCtx)).rejects.toThrow(/owner_id.*system-managed/);
});
it('insert with owner_id = self passes without any transfer grant', async () => {
const harness = await boot([memberSet]);
const opCtx: any = {
object: 'task', operation: 'insert', data: { name: 'A', owner_id: 'u1' },
context: memberCtx(),
};
await harness.run(opCtx);
expect(opCtx.data.owner_id).toBe('u1');
});
it('insert forging another owner passes with allowTransfer', async () => {
const harness = await boot([memberSet, transferSet]);
const opCtx: any = {
object: 'task', operation: 'insert', data: { name: 'A', owner_id: 'colleague' },
context: memberCtx({ permissions: ['can_transfer'] }),
};
await harness.run(opCtx);
expect(opCtx.data.owner_id).toBe('colleague');
});
it('insert forging another owner passes with modifyAllRecords (implies transfer)', async () => {
const harness = await boot([memberSet, modifyAllSet]);
const opCtx: any = {
object: 'task', operation: 'insert', data: { name: 'A', owner_id: 'colleague' },
context: memberCtx({ permissions: ['org_admin_like'] }),
};
await harness.run(opCtx);
expect(opCtx.data.owner_id).toBe('colleague');
});
it('batch insert: empty owners are stamped per row, a forged row denies the batch', async () => {
const harness = await boot([memberSet]);
const stamped: any = {
object: 'task', operation: 'insert', data: [{ name: 'a' }, { name: 'b', owner_id: '' }],
context: memberCtx(),
};
await harness.run(stamped);
expect(stamped.data.map((r: any) => r.owner_id)).toEqual(['u1', 'u1']);
const forged: any = {
object: 'task', operation: 'insert', data: [{ name: 'a' }, { name: 'b', owner_id: 'victim' }],
context: memberCtx(),
};
await expect(harness.run(forged)).rejects.toThrow(/owner_id.*system-managed/);
});
it('update transferring ownership is denied for a plain member', async () => {
const harness = await boot([memberSet], () => ({ id: 't1', owner_id: 'u1' }));
const opCtx: any = {
object: 'task', operation: 'update', data: { id: 't1', owner_id: 'admin' },
context: memberCtx(),
};
await expect(harness.run(opCtx)).rejects.toThrow(/owner_id.*system-managed/);
});
it('update disowning (owner_id: null) is denied for a plain member', async () => {
const harness = await boot([memberSet], () => ({ id: 't1', owner_id: 'u1' }));
const opCtx: any = {
object: 'task', operation: 'update', data: { id: 't1', owner_id: null },
context: memberCtx(),
};
await expect(harness.run(opCtx)).rejects.toThrow(/owner_id.*system-managed/);
});
it('update echoing the unchanged owner back (form save) is tolerated', async () => {
const harness = await boot([memberSet], () => ({ id: 't1', owner_id: 'u1' }));
const opCtx: any = {
object: 'task', operation: 'update', data: { id: 't1', name: 'renamed', owner_id: 'u1' },
context: memberCtx(),
};
await harness.run(opCtx); // must not throw
});
it('update transferring ownership passes with allowTransfer', async () => {
const harness = await boot([memberSet, transferSet], () => ({ id: 't1', owner_id: 'u1' }));
const opCtx: any = {
object: 'task', operation: 'update', data: { id: 't1', owner_id: 'colleague' },
context: memberCtx({ permissions: ['can_transfer'] }),
};
await harness.run(opCtx);
expect(opCtx.data.owner_id).toBe('colleague');
});
it('bulk update carrying owner_id fails closed for a plain member (no pre-image to compare)', async () => {
const harness = await boot([memberSet]);
const opCtx: any = {
object: 'task', operation: 'update', data: { owner_id: 'u1' },
options: { where: { status: 'open' }, multi: true },
context: memberCtx(),
};
await expect(harness.run(opCtx)).rejects.toThrow(/owner_id.*system-managed/);
});
it('update without owner_id in the change-set is untouched by the guard', async () => {
// [#21771] The addressed by-id update now asks the read door whether the
// caller can read `t1`, so the double answers that read with the row.
const harness = await boot([memberSet], () => ({ id: 't1', owner_id: 'u1' }));
const opCtx: any = {
object: 'task', operation: 'update', data: { id: 't1', name: 'renamed' },
context: memberCtx(),
};
await harness.run(opCtx); // must not throw — the guard reads no owner here
});
it('update disowning via owner_id:undefined is denied (mongo $set null hazard)', async () => {
const harness = await boot([memberSet], () => ({ id: 't1', owner_id: 'u1' }));
const opCtx: any = {
object: 'task', operation: 'update', data: { id: 't1', owner_id: undefined },
context: memberCtx(),
};
await expect(harness.run(opCtx)).rejects.toThrow(/owner_id.*system-managed/);
});
it('insert with a NON-SCALAR owner_id (array) is denied, not coerced to self', async () => {
const harness = await boot([memberSet]);
const opCtx: any = {
object: 'task', operation: 'insert', data: { name: 'A', owner_id: ['u1'] },
context: memberCtx(),
};
// String(['u1']) === 'u1' would have passed as self; scalar-only rejects it.
await expect(harness.run(opCtx)).rejects.toThrow(/owner_id.*system-managed/);
});
it('update echo with a NON-SCALAR owner_id equal-by-coercion is denied', async () => {
const harness = await boot([memberSet], () => ({ id: 't1', owner_id: 'u1' }));
const opCtx: any = {
object: 'task', operation: 'update', data: { id: 't1', owner_id: ['u1'] },
context: memberCtx(),
};
await expect(harness.run(opCtx)).rejects.toThrow(/owner_id.*system-managed/);
});
it('array-shaped update change-set carrying owner_id fails closed (no silent bypass)', async () => {
const harness = await boot([memberSet]);
const opCtx: any = {
object: 'task', operation: 'update', data: [{ id: 't1', owner_id: 'attacker' }],
context: memberCtx(),
};
await expect(harness.run(opCtx)).rejects.toThrow(/owner_id.*system-managed/);
});
it('a prototype-chain owner_id (not own property) does not trip the guard', async () => {
// [#21771] The double answers the addressed write's read question with the row.
const harness = await boot([memberSet], () => ({ id: 't1', owner_id: 'u1' }));
const proto = { owner_id: 'attacker' };
const data: any = Object.create(proto);
data.id = 't1';
data.name = 'renamed'; // only own props; owner_id is inherited
const opCtx: any = { object: 'task', operation: 'update', data, context: memberCtx() };
await harness.run(opCtx); // must not throw — owner_id is not an own property
});
it('[#3023] an engine referential FK clear (__referentialFieldClear) is exempt — owner_id:null cascade is allowed for a plain member', async () => {
// cascadeDeleteRelations nulls owner_id on dependents when the referenced
// sys_user is deleted; that integrity write must not be blocked by the
// disown guard. The same payload WITHOUT the marker is denied (covered
// by the disown test above).
const harness = await boot([memberSet], () => ({ id: 't1', owner_id: 'someone' }));
const opCtx: any = {
object: 'task', operation: 'update', data: { id: 't1', owner_id: null },
context: memberCtx({ __referentialFieldClear: true }),
};
await harness.run(opCtx); // must not throw — engine-internal referential clear
});
});
// -------------------------------------------------------------------------
// [ADR-0138 D1] The owner-anchor stamp's GUEST branch: the guest is a
// principal, never an owner. The anonymous principal is stamped with
// nothing, its empty owner stays unset, and an owner it supplies is refused
// on insert and on update WHATEVER it is granted — the sets below carry the
// transfer bit and `modifyAllRecords`, which the anchor tier keeps off a real
// guest binding, precisely so the refusal is shown not to lean on that tier.
// Every refusal carries its control: the same write by a signed-in member,
// and the same guest write without the owner. The door-level pins, on a
// booted stack, are `packages/qa/dogfood/test/guest-owner-stamp.dogfood.test.ts`.
// -------------------------------------------------------------------------
describe('owner_id anchor guard — the guest branch (ADR-0138 D1)', () => {
const guestWriter: PermissionSet = {
name: 'synth_guest_writer',
label: 'Guest writer',
objects: { task: { allowRead: true, allowCreate: true } },
} as any;
const guestTransfer: PermissionSet = {
name: 'synth_guest_transfer',
label: 'Guest writer with transfer',
objects: { task: { allowRead: true, allowCreate: true, allowEdit: true, allowTransfer: true } },
} as any;
const guestModifyAll: PermissionSet = {
name: 'synth_guest_modify_all',
label: 'Guest writer with modify-all',
objects: { task: { allowRead: true, allowCreate: true, allowEdit: true, modifyAllRecords: true } },
} as any;
const memberSet: PermissionSet = {
name: 'member_default',
label: 'Member',
objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true } },
} as any;
const memberTransfer: PermissionSet = {
name: 'can_transfer',
label: 'Transfer',
objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowTransfer: true } },
} as any;
const ALL = [guestWriter, guestTransfer, guestModifyAll, memberSet, memberTransfer];
const boot = async (findOneImpl?: (query: any) => any) => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({ permissionSets: ALL, findOneImpl });
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
return harness;
};
const guestCtx = (permissions: string[]) =>
({ principalKind: 'guest', positions: ['guest'], isSystem: false, permissions, tenantId: 'org-1' });
const memberCtx = (permissions: string[] = []) =>
({ principalKind: 'human', userId: 'u1', tenantId: 'org-1', positions: [], permissions });
/** The middleware's verdict: admitted, or the refusal's ADR-0112 `code` + `status`. */
const verdict = async (harness: { run(opCtx: any): Promise<any> }, opCtx: any) => {
try {
await harness.run(opCtx);
return { admitted: true } as const;
} catch (e) {
const err = e as { code?: unknown; status?: unknown };
return { admitted: false, code: err.code, status: err.status } as const;
}
};
const REFUSED = { admitted: false, code: 'PERMISSION_DENIED', status: 403 } as const;
const GUEST_GRANTS: Array<[string, string[]]> = [
['create only', [guestWriter.name]],
['the transfer bit', [guestTransfer.name]],
['modifyAllRecords', [guestModifyAll.name]],
];
const FORGED_OWNERS = ['u_victim', 'usr_system', 'guest'];
it('a guest insert with no owner is stamped with nothing — the row stays unset', async () => {
const harness = await boot();
const opCtx: any = { object: 'task', operation: 'insert', data: { name: 'A' }, context: guestCtx([guestWriter.name]) };
expect(await verdict(harness, opCtx)).toEqual({ admitted: true });
expect(opCtx.data).not.toHaveProperty('owner_id');
// Control: the stamp is live — a signed-in member's same insert is stamped.
const member: any = { object: 'task', operation: 'insert', data: { name: 'A' }, context: memberCtx() };
expect(await verdict(harness, member)).toEqual({ admitted: true });
expect(member.data.owner_id).toBe('u1');
});
it('a guest\'s empty owner (null or an empty string) is left unset, never a value', async () => {
const harness = await boot();
for (const empty of [null, '']) {
const opCtx: any = {
object: 'task', operation: 'insert', data: { name: 'A', owner_id: empty }, context: guestCtx([guestWriter.name]),
};
expect(await verdict(harness, opCtx), JSON.stringify(empty)).toEqual({ admitted: true });
expect(opCtx.data.owner_id, JSON.stringify(empty)).toBeNull();
}
});
it('a guest-supplied owner is refused 403 PERMISSION_DENIED on insert, whatever the guest holds', async () => {
const harness = await boot();
for (const [grant, permissions] of GUEST_GRANTS) {
for (const owner of FORGED_OWNERS) {
const opCtx: any = {
object: 'task', operation: 'insert', data: { name: 'A', owner_id: owner }, context: guestCtx(permissions),
};
expect(await verdict(harness, opCtx), `${grant} / ${owner}`).toEqual(REFUSED);
}
// Control: the same guest, the same grant, no owner — admitted.
const plain: any = { object: 'task', operation: 'insert', data: { name: 'A' }, context: guestCtx(permissions) };
expect(await verdict(harness, plain), grant).toEqual({ admitted: true });
}
// Control: a member holding the transfer grant sets the same owner.
const member: any = {
object: 'task', operation: 'insert', data: { name: 'A', owner_id: 'u_victim' }, context: memberCtx([memberTransfer.name]),
};
expect(await verdict(harness, member)).toEqual({ admitted: true });
expect(member.data.owner_id).toBe('u_victim');
});
it('batch: one guest-supplied owner refuses the whole batch, and empty rows stay unset', async () => {
const harness = await boot();
const forged: any = {
object: 'task', operation: 'insert', data: [{ name: 'a' }, { name: 'b', owner_id: 'u_victim' }],
context: guestCtx([guestTransfer.name]),
};
expect(await verdict(harness, forged)).toEqual(REFUSED);
const clean: any = {
object: 'task', operation: 'insert', data: [{ name: 'a' }, { name: 'b', owner_id: '' }],
context: guestCtx([guestTransfer.name]),
};
expect(await verdict(harness, clean)).toEqual({ admitted: true });
expect(clean.data.map((r: any) => r.owner_id ?? null)).toEqual([null, null]);
});
it('a guest update carrying an owner is refused — a transfer, a disown and an echo alike — whatever it holds', async () => {
const harness = await boot(() => ({ id: 't1', owner_id: 'u_victim' }));
for (const [grant, permissions] of GUEST_GRANTS.slice(1)) {
for (const owner of ['u_other', null, 'u_victim']) {
const opCtx: any = {
object: 'task', operation: 'update', data: { id: 't1', owner_id: owner }, context: guestCtx(permissions),
};
expect(await verdict(harness, opCtx), `${grant} / ${JSON.stringify(owner)}`).toEqual(REFUSED);
}
// Control: the same guest's update without the owner is admitted.
const plain: any = { object: 'task', operation: 'update', data: { id: 't1', name: 'renamed' }, context: guestCtx(permissions) };
expect(await verdict(harness, plain), grant).toEqual({ admitted: true });
}
// Control: a member holding the transfer grant transfers the same row.
const member: any = {
object: 'task', operation: 'update', data: { id: 't1', owner_id: 'u_other' }, context: memberCtx([memberTransfer.name]),
};
expect(await verdict(harness, member)).toEqual({ admitted: true });
});
});
// -------------------------------------------------------------------------
// [ADR-0095 D1 / #2937 Finding 1] step 3.7 — the Layer 0 tenant wall on the
// WRITE post-image. A SUPPLIED (non-empty) `organization_id` in an insert /
// update payload must satisfy the same Layer 0 filter the read side uses;
// a forged (insert) or re-pointed (update) value that would land the row in
// another tenant is denied fail-closed. Previously only the read-side Layer 0
// and the multitenant dogfood covered this — these are the package-level
// write-side unit tests for the wall.
//
// A plain-CRUD permission set with NO `tenant_isolation` RLS policy is used on
// purpose, so Layer 0 (step 3.7) — not a business RLS `check` (step 3.6) — is
// the sole enforcer under test. `orgScoping: true` flips
// `SecurityPlugin.orgScopingEnabled`, which is what makes Layer 0 active.
// -------------------------------------------------------------------------
describe('organization_id tenant wall on writes (step 3.7)', () => {
const memberSet: PermissionSet = {
name: 'member_default',
label: 'Member',
objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } },
} as any;
const boot = async (findOneImpl?: (query: any) => any) => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({ permissionSets: [memberSet], orgScoping: true, findOneImpl });
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
return harness;
};
const memberCtx = (extra: Record<string, unknown> = {}) =>
({ userId: 'u1', tenantId: 'org-1', positions: [], permissions: [], ...extra });
it('insert forging a cross-tenant organization_id is denied', async () => {
const harness = await boot();
const opCtx: any = {
object: 'task', operation: 'insert', data: { name: 'A', organization_id: 'org-2' },
context: memberCtx(),
};
await expect(harness.run(opCtx)).rejects.toThrow(/would place .* in another tenant/);
});
it("insert supplying the caller's own organization_id passes", async () => {
const harness = await boot();
const opCtx: any = {
object: 'task', operation: 'insert', data: { name: 'A', organization_id: 'org-1' },
context: memberCtx(),
};
await harness.run(opCtx); // must not throw
expect(opCtx.data.organization_id).toBe('org-1');
});
it('update re-pointing organization_id to another tenant is denied', async () => {
// Pre-image is visible (in-tenant), so step 2.7 passes and 3.7 is reached.
const harness = await boot(() => ({ id: 't1', organization_id: 'org-1' }));
const opCtx: any = {
object: 'task', operation: 'update', data: { id: 't1', organization_id: 'org-2' },
context: memberCtx(),
};
await expect(harness.run(opCtx)).rejects.toThrow(/would place .* in another tenant/);
});
it("update echoing the caller's own organization_id passes", async () => {
const harness = await boot(() => ({ id: 't1', organization_id: 'org-1' }));
const opCtx: any = {
object: 'task', operation: 'update', data: { id: 't1', name: 'renamed', organization_id: 'org-1' },
context: memberCtx(),
};
await harness.run(opCtx); // must not throw
});
it("a write that doesn't supply organization_id is untouched (auto-stamp's job)", async () => {
const harness = await boot();
const opCtx: any = {
object: 'task', operation: 'insert', data: { name: 'A' },
context: memberCtx(),
};
await harness.run(opCtx); // must not throw — no cross-tenant check on an absent value
// [ADR-0105 D5/D12] SecurityPlugin never stamps organization_id. That stays
// with the organizations runtime, which is also what activates a
// walled posture — so a forged `org-scoping` registration yields NULL-org
// rows the wall hides (a broken deployment), not a working unlicensed one.
expect(opCtx.data.organization_id).toBeUndefined();
});
it('[ADR-0105 D5] a BULK insert leaves rows that omit organization_id untouched', async () => {
const harness = await boot();
const opCtx: any = {
object: 'task', operation: 'insert',
data: [{ name: 'A' }, { name: 'B', organization_id: 'org-1' }],
context: memberCtx(),
};
await harness.run(opCtx);
expect(opCtx.data.map((r: any) => r.organization_id)).toEqual([undefined, 'org-1']);
});
it('[ADR-0105 D5] a BULK insert with ONE forged row is denied entirely', async () => {
// The pre-D5 check required a non-array payload, so an array of rows could
// carry a forged organization_id past the wall — the #2937 defect one call
// site down. No partial landing: one bad row denies the write.
const harness = await boot();
const opCtx: any = {
object: 'task', operation: 'insert',
data: [{ name: 'A', organization_id: 'org-1' }, { name: 'B', organization_id: 'org-2' }],
context: memberCtx(),
};
await expect(harness.run(opCtx)).rejects.toThrow(/another tenant|organization scope/i);
});
it('a system-context write bypasses the wall (import / migration / SYSTEM_CTX)', async () => {
const harness = await boot();
const opCtx: any = {
object: 'task', operation: 'insert', data: { name: 'A', organization_id: 'org-2' },
context: memberCtx({ isSystem: true }),
};
await harness.run(opCtx); // isSystem short-circuits the whole middleware — legit cross-org moves unaffected
});
});
// [ADR-0105 D3] Stripping is decided by PROVENANCE, not by pattern-matching
// the `current_user.organization_id` token. `tenantPolicySet` above is an
// APP-AUTHORED fixture, so with isolation off it is now RETAINED and fails
// closed at compile time — it is no longer silently dropped (finding F1, the
// ADR-0049 "declared but unenforced" class). Only the platform's own shipped
// tenant policies are stripped; that half is covered in
// `platform-tenant-policies.test.ts`.
it('without org-scoping — an APP-AUTHORED tenant policy is RETAINED (never silently dropped)', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({ permissionSets: [tenantPolicySet] });
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const opCtx: any = {
object: 'task', operation: 'find', ast: { where: undefined },
context: { userId: 'u1', tenantId: 'org-1', positions: [], permissions: [] },
};
await harness.run(opCtx);
// Layer 0 is inert (no wall), so this filter is the AUTHORED policy alone.
expect(opCtx.ast.where).toEqual({ organization_id: 'org-1' });
// ...and the operator is told why, once.
expect(harness.ctx.logger.warn).toHaveBeenCalledWith(
expect.stringContaining('ADR-0105'),
expect.objectContaining({ object: 'task', policy: 'tenant_isolation' }),
);
});
it('without org-scoping — a retained authored tenant policy FAILS CLOSED with no active org', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({ permissionSets: [tenantPolicySet] });
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const opCtx: any = {
object: 'task', operation: 'find', ast: { where: undefined },
context: { userId: 'u1', positions: [], permissions: [] },
};
await harness.run(opCtx);
// The context variable is unavailable → the policy drops out at compile
// time → deny sentinel. Zero rows, loudly — never fail-open.
expect(opCtx.ast.where).toEqual(RLS_DENY_FILTER);
});
it('with org-scoping plugin — applies tenant_isolation RLS to find', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({ permissionSets: [tenantPolicySet], orgScoping: true });
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const opCtx: any = {
object: 'task', operation: 'find', ast: { where: undefined },
context: { userId: 'u1', tenantId: 'org-1', positions: [], permissions: [] },
};
await harness.run(opCtx);
// [ADR-0095 D1] Layer 0 (the tenant wall) AND the fixture's own legacy
// tenant_isolation policy (Layer 1) — same rows. Production seeds no longer
// carry the Layer-1 tenant policy, so in production this is Layer 0's
// `{organization_id}` alone; this fixture keeps it to exercise composition.
expect(opCtx.ast.where).toEqual({ $and: [{ organization_id: 'org-1' }, { organization_id: 'org-1' }] });
});
// Regression: when a schema explicitly opts out of tenancy
// (`tenancy.enabled === false` — e.g. `sys_package` Marketplace catalog),
// the wildcard `tenant_isolation` policy targeting `organization_id`
// must be treated as "not applicable" and SKIPPED, NOT fail-closed
// with RLS_DENY_FILTER. Otherwise the registry skips injecting the
// tenant column (correct) but the security plugin still produces zero
// rows on every read (wrong) — which silently broke the cloud
// Marketplace UI.
it('tenancy.enabled=false — wildcard organization_id RLS is skipped, not denied', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [tenantPolicySet],
// Catalog table without organization_id; opts out of tenancy.
objectFields: ['id', 'manifest_id', 'visibility', 'owner_org_id'],
schemaExtra: { tenancy: { enabled: false } },
orgScoping: true,
});
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const opCtx: any = {
object: 'task', operation: 'find', ast: { where: undefined },
context: { userId: 'u1', tenantId: 'org-1', positions: [], permissions: [] },
};
await harness.run(opCtx);
// No deny sentinel, no organization_id where clause: the read
// passes through and the catalog row is visible to every tenant.
expect(opCtx.ast.where).toBeUndefined();
});
// ── publicFormGrant — server-managed anchor stripping (#3022) ───────────
// The ADR-0056 Option A grant short-circuits the middleware BEFORE every
// write gate (FLS 2.5, owner anchor 3.5, tenant CHECK), so the grant branch
// itself must force the system-managed anchors: an anonymous public-form
// insert can never forge `owner_id` / `organization_id` / audit columns,
// no matter what the route-side field allow-list let through.
describe('publicFormGrant — server-managed anchor stripping (#3022)', () => {
const anonFormCtx = { publicFormGrant: { object: 'task' }, permissions: ['guest_portal'], anonymous: true };
const boot = async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({ permissionSets: [tenantPolicySet] });
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
return harness;
};
it('strips forged owner_id / organization_id / audit anchors from an insert', async () => {
const harness = await boot();
const opCtx: any = {
object: 'task', operation: 'insert',
data: {
name: 'Ada', id: 'rec_forged', owner_id: 'usr_victim', organization_id: 'org_victim',
created_by: 'usr_victim', updated_by: 'usr_victim',
created_at: '2020-01-01T00:00:00Z', updated_at: '2020-01-01T00:00:00Z',
},
context: anonFormCtx,
};
await harness.run(opCtx);
// Business fields survive; every server-managed anchor is gone
// (ownership stays unset for hooks / first-admin bootstrap to assign).
expect(opCtx.data).toEqual({ name: 'Ada' });
});
it('strips anchors from EVERY row of a batch insert', async () => {
const harness = await boot();
const opCtx: any = {
object: 'task', operation: 'insert',
data: [
{ name: 'A', owner_id: 'usr_victim' },
{ name: 'B', organization_id: 'org_victim' },
{ name: 'C' },
],
context: anonFormCtx,
};
await harness.run(opCtx);
expect(opCtx.data).toEqual([{ name: 'A' }, { name: 'B' }, { name: 'C' }]);
});
it('a clean insert passes through untouched', async () => {
const harness = await boot();
const opCtx: any = {
object: 'task', operation: 'insert',
data: { name: 'Ada', email: 'ada@example.com' },