-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsecurity-plugin.test.ts
More file actions
1099 lines (1021 loc) · 48.4 KB
/
Copy pathsecurity-plugin.test.ts
File metadata and controls
1099 lines (1021 loc) · 48.4 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 { SecurityPlugin } from './security-plugin.js';
import { PermissionEvaluator } from './permission-evaluator.js';
import { FieldMasker } from './field-masker.js';
import { RLSCompiler, RLS_DENY_FILTER } from './rls-compiler.js';
import type { PermissionSet } from '@objectstack/spec/security';
// ---------------------------------------------------------------------------
// 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();
});
// -------------------------------------------------------------------------
// 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 }) => {
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).
const findOne = vi.fn(async (_object: string, query: any) =>
overrides.findOneImpl ? overrides.findOneImpl(query) : null,
);
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,
};
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' };
}
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, async () => {});
return opCtx;
},
};
};
const tenantPolicySet: PermissionSet = {
name: 'member_default',
label: 'Member',
isProfile: true,
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);
const opCtx: any = {
object: 'task', operation: 'insert', data: { name: 'A' },
context: { userId: 'u1', tenantId: 'org-1', roles: [], permissions: [] },
};
await harness.run(opCtx);
// SecurityPlugin no longer touches organization_id — that's plugin-org-scoping's job.
expect(opCtx.data.organization_id).toBeUndefined();
expect(opCtx.data.owner_id).toBe('u1');
});
it('without org-scoping plugin — strips tenant_isolation RLS so find applies no tenant where', 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', roles: [], permissions: [] },
};
await harness.run(opCtx);
expect(opCtx.ast.where).toBeUndefined();
});
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', roles: [], permissions: [] },
};
await harness.run(opCtx);
expect(opCtx.ast.where).toEqual({ 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, strategy: 'shared' } },
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', roles: [], 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();
});
// ── Row-level WRITE authorization (pre-image check, #1985) ──────────────
// A by-id update/delete never builds an RLS `where`, so the owner/tenant
// predicate must be enforced by re-reading the target row before mutating.
describe('pre-image write authorization', () => {
const ownerPolicySet: PermissionSet = {
name: 'member_default',
label: 'Member',
isProfile: true,
objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } },
rowLevelSecurity: [
{ name: 'owner_only_writes', object: '*', operation: 'update', using: 'created_by = current_user.id' },
{ name: 'owner_only_deletes', object: '*', operation: 'delete', using: 'created_by = current_user.id' },
],
} as any;
const memberCtx = { userId: 'u1', tenantId: 'org-1', roles: [], permissions: [] };
const ownerFields = ['id', 'created_by', 'name'];
it('DENIES an update when the target row is not visible under the write filter (not the owner)', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [ownerPolicySet],
objectFields: ownerFields,
findOneImpl: () => null, // row exists but filtered out by created_by → not visible
});
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const opCtx: any = {
object: 'task', operation: 'update',
data: { id: 'r1', name: 'hijack' }, options: { where: { id: 'r1' } },
context: memberCtx,
};
await expect(harness.run(opCtx)).rejects.toMatchObject({ name: 'PermissionDeniedError' });
expect(harness.findOne).toHaveBeenCalledTimes(1);
// the re-read ANDs the row id with the owner write filter
const [, query] = harness.findOne.mock.calls[0];
expect(query.where.$and[0]).toEqual({ id: 'r1' });
});
it('ALLOWS an update when the target row IS visible under the write filter (the owner)', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [ownerPolicySet],
objectFields: ownerFields,
findOneImpl: () => ({ id: 'r1', created_by: 'u1', name: 'mine' }),
});
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const opCtx: any = {
object: 'task', operation: 'delete',
options: { where: { id: 'r1' } },
context: memberCtx,
};
await expect(harness.run(opCtx)).resolves.toBeDefined();
expect(harness.findOne).toHaveBeenCalledTimes(1);
});
it('SKIPS the check when no RLS policy applies (e.g. modifyAllRecords / admin) — no extra read', async () => {
const adminSet: PermissionSet = {
name: 'admin_full_access', label: 'Admin', isProfile: true,
objects: { '*': { allowRead: true, allowEdit: true, allowDelete: true, modifyAllRecords: true, viewAllRecords: true } },
// no rowLevelSecurity
} as any;
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'admin_full_access' });
const harness = makeMiddlewareCtx({ permissionSets: [adminSet], objectFields: ownerFields });
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const opCtx: any = {
object: 'task', operation: 'update',
data: { id: 'r1', name: 'x' }, options: { where: { id: 'r1' } },
context: { userId: 'admin', roles: ['admin_full_access'], permissions: [] },
};
await expect(harness.run(opCtx)).resolves.toBeDefined();
expect(harness.findOne).not.toHaveBeenCalled();
});
it('SKIPS the check for a multi-row predicate id ({$in}) — only single-id by-pk writes are guarded', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [ownerPolicySet], objectFields: ownerFields, findOneImpl: () => null,
});
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const opCtx: any = {
object: 'task', operation: 'update', multi: true,
data: { name: 'bulk' }, options: { multi: true, where: { id: { $in: ['r1', 'r2'] } } },
context: memberCtx,
};
await harness.run(opCtx);
expect(harness.findOne).not.toHaveBeenCalled();
});
});
it('tenancy.enabled=false via systemFields.tenant=false — also skipped', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [tenantPolicySet],
objectFields: ['id', 'name'],
schemaExtra: { systemFields: { tenant: 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', roles: [], permissions: [] },
};
await harness.run(opCtx);
expect(opCtx.ast.where).toBeUndefined();
});
it('tenancy enabled (default) — wildcard organization_id RLS still denies when field is missing', async () => {
// Sanity check: dropping the deny sentinel must remain in effect
// for objects that did NOT opt out — otherwise a wildcard policy
// applied to a half-migrated table would silently expose every row.
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [tenantPolicySet],
objectFields: ['id', 'name'], // no organization_id, no opt-out
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', roles: [], permissions: [] },
};
await harness.run(opCtx);
expect(opCtx.ast.where).toEqual(RLS_DENY_FILTER);
});
// Post-resolution fallback: roles is non-empty (e.g. better-auth
// sys_member.role = 'owner') but no sys_role binding maps that name to
// a permission set, so resolvePermissionSets returns []. Without the
// post-resolution fallback both CRUD and RLS would be skipped → users
// with org membership but no granted permission set could read every
// tenant's data. The fallback re-resolves with `member_default` so
// tenant_isolation still applies.
it('post-resolution fallback — non-empty roles resolving to no permission sets still get tenant_isolation RLS', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
// The metadata only carries `member_default` (loaded via
// `permissionSets: [tenantPolicySet]`). The role name 'owner' is
// not bound anywhere, so `resolvePermissionSets(['owner'])` → [].
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', roles: ['owner'], permissions: [] },
};
await harness.run(opCtx);
expect(opCtx.ast.where).toEqual({ organization_id: 'org-1' });
});
// -------------------------------------------------------------------------
// getReadFilter service (ADR-0021 D-C) — the reusable READ scope the
// analytics raw-SQL path bridges to. Must produce the SAME FilterCondition
// the engine middleware injects on `find`, and fail CLOSED on any error.
// -------------------------------------------------------------------------
describe('getReadFilter service', () => {
it('registers a "security" service exposing getReadFilter', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({ permissionSets: [tenantPolicySet] });
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const call = (harness.ctx.registerService as any).mock.calls.find(
(c: any[]) => c[0] === 'security',
);
expect(call).toBeTruthy();
expect(typeof call[1].getReadFilter).toBe('function');
});
it('returns the SAME tenant filter the find-path injects (org-scoping on)', 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 ctx = { userId: 'u1', tenantId: 'org-1', roles: [], permissions: [] };
const filter = await plugin.getReadFilter('task', ctx);
expect(filter).toEqual({ organization_id: 'org-1' });
});
it('returns undefined (no scope) when tenant_isolation is stripped (org-scoping off)', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({ permissionSets: [tenantPolicySet] });
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const filter = await plugin.getReadFilter('task', { userId: 'u1', tenantId: 'org-1', roles: [], permissions: [] });
expect(filter).toBeUndefined();
});
it('fail-closed: wildcard org policy on an object missing the column → deny sentinel', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [tenantPolicySet],
objectFields: ['id', 'name'], // no organization_id, tenancy not opted out
orgScoping: true,
});
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const filter = await plugin.getReadFilter('task', { userId: 'u1', tenantId: 'org-1', roles: [], permissions: [] });
expect(filter).toEqual(RLS_DENY_FILTER);
});
it('tenancy opt-out → undefined (not denied), matching the find-path', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [tenantPolicySet],
objectFields: ['id', 'name'],
schemaExtra: { tenancy: { enabled: false, strategy: 'shared' } },
orgScoping: true,
});
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const filter = await plugin.getReadFilter('task', { userId: 'u1', tenantId: 'org-1', roles: [], permissions: [] });
expect(filter).toBeUndefined();
});
it('system context bypasses scoping (returns undefined)', 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 filter = await plugin.getReadFilter('task', { isSystem: true, userId: 'u1', tenantId: 'org-1' });
expect(filter).toBeUndefined();
});
it('anonymous (no userId/roles/permissions) → undefined (authn gated elsewhere)', 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 filter = await plugin.getReadFilter('task', { roles: [], permissions: [] });
expect(filter).toBeUndefined();
});
it('fail-closed: a permission-resolution throw yields the deny sentinel (never allow-all)', 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);
// Force resolution to blow up.
(plugin as any).permissionEvaluator.resolvePermissionSets = async () => {
throw new Error('metadata service unavailable');
};
const filter = await plugin.getReadFilter('task', { userId: 'u1', tenantId: 'org-1', roles: [], permissions: [] });
expect(filter).toEqual(RLS_DENY_FILTER);
});
});
// -------------------------------------------------------------------------
// FLS write enforcement (Backend FLS strip — gap #1)
// -------------------------------------------------------------------------
// Permission set that allows full CRUD on `task` but denies edit on
// two specific fields: `salary` (read-only) and `ssn` (hidden).
const flsPolicySet: PermissionSet = {
name: 'member_default',
label: 'Member',
isProfile: true,
objects: {
'*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true },
},
fields: {
'task.salary': { readable: true, editable: false },
'task.ssn': { readable: false, editable: false },
},
} as any;
it('FLS write — insert with a forbidden field throws PermissionDeniedError', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [flsPolicySet],
objectFields: ['id', 'owner_id', 'name', 'salary', 'ssn'],
});
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const opCtx: any = {
object: 'task',
operation: 'insert',
data: { name: 'A', salary: 9999 },
context: { userId: 'u1', tenantId: 'org-1', roles: [], permissions: ['member_default'] },
};
await expect(harness.run(opCtx)).rejects.toThrow(/Field write denied/);
await expect(harness.run(opCtx)).rejects.toMatchObject({
details: { forbiddenFields: ['salary'] },
});
});
it('FLS write — update with a forbidden field throws PermissionDeniedError', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [flsPolicySet],
objectFields: ['id', 'owner_id', 'name', 'salary', 'ssn'],
});
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const opCtx: any = {
object: 'task',
operation: 'update',
data: { ssn: 'leaked-123' },
context: { userId: 'u1', tenantId: 'org-1', roles: [], permissions: ['member_default'] },
};
await expect(harness.run(opCtx)).rejects.toMatchObject({
details: { forbiddenFields: ['ssn'] },
});
});
it('fails CLOSED when permission resolution throws — denies, never bypasses (P0-2)', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({ permissionSets: [tenantPolicySet] });
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
// Simulate the permission/metadata subsystem failing mid-resolution.
(plugin as any).permissionEvaluator = {
resolvePermissionSets: async () => { throw new Error('metadata service unavailable'); },
};
const opCtx: any = {
object: 'task',
operation: 'find',
data: {},
context: { userId: 'u1', tenantId: 'org-1', roles: ['member'], permissions: [] },
};
// Resolution failed → the request must be DENIED, not waved through.
await expect(harness.run(opCtx)).rejects.toThrow(/permission subsystem unavailable/);
expect(harness.ctx.logger.error).toHaveBeenCalled();
});
it('a system operation still bypasses security regardless (P0-2)', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({ permissionSets: [tenantPolicySet] });
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
(plugin as any).permissionEvaluator = {
resolvePermissionSets: async () => { throw new Error('should not be called'); },
};
const opCtx: any = { object: 'task', operation: 'find', context: { isSystem: true } };
await expect(harness.run(opCtx)).resolves.toBeDefined(); // bypass short-circuits before resolution
});
it('FLS write — multiple forbidden fields are all listed in the error', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [flsPolicySet],
objectFields: ['id', 'owner_id', 'name', 'salary', 'ssn'],
});
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const opCtx: any = {
object: 'task',
operation: 'insert',
data: { name: 'A', salary: 1, ssn: 'x' },
context: { userId: 'u1', tenantId: 'org-1', roles: [], permissions: ['member_default'] },
};
await expect(harness.run(opCtx)).rejects.toMatchObject({
details: { forbiddenFields: ['salary', 'ssn'] },
});
});
it('FLS write — insert that touches only editable fields passes', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [flsPolicySet],
objectFields: ['id', 'owner_id', 'name', 'salary', 'ssn'],
});
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const opCtx: any = {
object: 'task',
operation: 'insert',
data: { name: 'A' },
context: { userId: 'u1', tenantId: 'org-1', roles: [], permissions: ['member_default'] },
};
await expect(harness.run(opCtx)).resolves.toBeTruthy();
// owner_id was auto-injected (still in scope for tests)
expect(opCtx.data.owner_id).toBe('u1');
});
it('FLS write — bulk insert array catches forbidden field on any row', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [flsPolicySet],
objectFields: ['id', 'owner_id', 'name', 'salary', 'ssn'],
});
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const opCtx: any = {
object: 'task',
operation: 'insert',
data: [
{ name: 'a' },
{ name: 'b', salary: 9 }, // offender on row 2
],
context: { userId: 'u1', tenantId: 'org-1', roles: [], permissions: ['member_default'] },
};
await expect(harness.run(opCtx)).rejects.toMatchObject({
details: { forbiddenFields: ['salary'] },
});
});
it('FLS write — system context (isSystem) bypasses the check entirely', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [flsPolicySet],
objectFields: ['id', 'owner_id', 'name', 'salary', 'ssn'],
});
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const opCtx: any = {
object: 'task',
operation: 'insert',
data: { name: 'A', salary: 9999, ssn: 'sys' },
context: { isSystem: true },
};
await expect(harness.run(opCtx)).resolves.toBeTruthy();
});
it('FLS write — fields without any rule pass through (allow-list semantics)', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [flsPolicySet],
objectFields: ['id', 'owner_id', 'name', 'salary', 'ssn', 'description'],
});
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
// `description` has no field rule → must be writable.
const opCtx: any = {
object: 'task',
operation: 'insert',
data: { name: 'A', description: 'foo' },
context: { userId: 'u1', tenantId: 'org-1', roles: [], permissions: ['member_default'] },
};
await expect(harness.run(opCtx)).resolves.toBeTruthy();
});
it('FLS write — does not interfere with read (find) — masker still strips read', async () => {
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
const harness = makeMiddlewareCtx({
permissionSets: [flsPolicySet],
objectFields: ['id', 'owner_id', 'name', 'salary', 'ssn'],
});
await plugin.init(harness.ctx);
await plugin.start(harness.ctx);
const opCtx: any = {
object: 'task',
operation: 'find',
ast: { where: undefined },
result: undefined,
context: { userId: 'u1', tenantId: 'org-1', roles: [], permissions: ['member_default'] },
};
// emulate the engine populating result inside next()
const orig = harness.run;
await orig.call(harness, opCtx);
// No throw — find is not a write operation.
});
});
// ---------------------------------------------------------------------------
describe('PermissionEvaluator', () => {
const makePermSet = (
name: string,
objects: PermissionSet['objects'] = {},
fields: PermissionSet['fields'] = {}
): PermissionSet => ({ name, objects, fields });
it('should allow read when allowRead is true', () => {
const evaluator = new PermissionEvaluator();
const ps = makePermSet('admin', { contact: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false } });
expect(evaluator.checkObjectPermission('find', 'contact', [ps])).toBe(true);
expect(evaluator.checkObjectPermission('findOne', 'contact', [ps])).toBe(true);
expect(evaluator.checkObjectPermission('count', 'contact', [ps])).toBe(true);
});
it('should deny when no permission set matches', () => {
const evaluator = new PermissionEvaluator();
const ps = makePermSet('readonly', { contact: { allowRead: false, allowCreate: false, allowEdit: false, allowDelete: false } });
expect(evaluator.checkObjectPermission('insert', 'contact', [ps])).toBe(false);
});
it('should allow unknown (non-destructive) operations by default', () => {
const evaluator = new PermissionEvaluator();
expect(evaluator.checkObjectPermission('unknownOp', 'contact', [])).toBe(true);
});
it('should fail CLOSED for unmapped destructive operations (ADR-0049)', () => {
const evaluator = new PermissionEvaluator();
// transfer/restore/purge are not in OPERATION_TO_PERMISSION; they must be
// denied rather than falling through to default-allow — even for an
// otherwise fully-permissioned set.
const ps = makePermSet('admin', {
contact: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, modifyAllRecords: true },
});
expect(evaluator.checkObjectPermission('transfer', 'contact', [ps])).toBe(false);
expect(evaluator.checkObjectPermission('restore', 'contact', [ps])).toBe(false);
expect(evaluator.checkObjectPermission('purge', 'contact', [ps])).toBe(false);
});
it('should allow via viewAllRecords', () => {
const evaluator = new PermissionEvaluator();
const ps = makePermSet('viewer', { task: { allowRead: false, allowCreate: false, allowEdit: false, allowDelete: false, viewAllRecords: true } });
expect(evaluator.checkObjectPermission('find', 'task', [ps])).toBe(true);
});
it('should allow edit/delete via modifyAllRecords', () => {
const evaluator = new PermissionEvaluator();
const ps = makePermSet('manager', { task: { allowRead: false, allowCreate: false, allowEdit: false, allowDelete: false, modifyAllRecords: true } });
expect(evaluator.checkObjectPermission('update', 'task', [ps])).toBe(true);
expect(evaluator.checkObjectPermission('delete', 'task', [ps])).toBe(true);
});
it('should merge field permissions (most permissive)', () => {
const evaluator = new PermissionEvaluator();
const ps1 = makePermSet('ps1', {}, { 'contact.email': { readable: true, editable: false } });
const ps2 = makePermSet('ps2', {}, { 'contact.email': { readable: false, editable: true } });
const result = evaluator.getFieldPermissions('contact', [ps1, ps2]);
expect(result['email']).toEqual({ readable: true, editable: true });
});
it('should filter field permissions to the correct object', () => {
const evaluator = new PermissionEvaluator();
const ps = makePermSet('ps', {}, {
'contact.email': { readable: true, editable: false },
'task.title': { readable: true, editable: true },
});
const result = evaluator.getFieldPermissions('contact', [ps]);
expect(result['email']).toBeDefined();
expect(result['title']).toBeUndefined();
});
it('should resolve permission sets from metadata service by role name', async () => {
const evaluator = new PermissionEvaluator();
const ps1 = { name: 'admin' };
const ps2 = { name: 'viewer' };
const metadata = { list: vi.fn().mockReturnValue([ps1, ps2]) };
const result = await evaluator.resolvePermissionSets(['admin'], metadata);
expect(result).toEqual([ps1]);
});
it('should return empty array when metadata has no permission sets', async () => {
const evaluator = new PermissionEvaluator();
const metadata = { list: vi.fn().mockReturnValue([]) };
await expect(
evaluator.resolvePermissionSets(['admin'], metadata),
).resolves.toEqual([]);
});
it('resolves permission sets via async metadata.list (real MetadataManager shape)', async () => {
const evaluator = new PermissionEvaluator();
const psAdmin = { name: 'admin_full_access' };
const metadata = {
list: vi.fn().mockResolvedValue([psAdmin, { name: 'viewer_readonly' }]),
};
const result = await evaluator.resolvePermissionSets(
['admin_full_access'],
metadata,
);
expect(metadata.list).toHaveBeenCalledWith('permission');
expect(result).toEqual([psAdmin]);
});
it('matches by both role and explicit permission-set identifiers', async () => {
const evaluator = new PermissionEvaluator();
const sets = [
{ name: 'admin_full_access' },
{ name: 'viewer_readonly' },
{ name: 'export_reports' },
];
const metadata = { list: vi.fn().mockReturnValue(sets) };
const result = await evaluator.resolvePermissionSets(
['admin_full_access', 'export_reports'],
metadata,
);
expect(result.map((p) => p.name).sort()).toEqual([
'admin_full_access',
'export_reports',
]);
});
});
// ---------------------------------------------------------------------------
// FieldMasker
// ---------------------------------------------------------------------------
describe('FieldMasker', () => {
it('should return results unchanged when no field permissions', () => {
const masker = new FieldMasker();
const records = [{ id: '1', name: 'Alice', email: 'alice@example.com' }];
expect(masker.maskResults(records, {}, 'contact')).toEqual(records);
});
it('should remove non-readable fields from records', () => {
const masker = new FieldMasker();
const records = [{ id: '1', name: 'Alice', email: 'alice@example.com' }];
const perms = { email: { readable: false, editable: false } };
const result = masker.maskResults(records, perms, 'contact') as any[];
expect(result[0].email).toBeUndefined();
expect(result[0].name).toBe('Alice');
});
it('should handle single record (non-array)', () => {
const masker = new FieldMasker();
const record = { id: '1', ssn: '123-45-6789', name: 'Bob' };
const perms = { ssn: { readable: false, editable: false } };
const result = masker.maskResults(record, perms, 'person') as any;
expect(result.ssn).toBeUndefined();
expect(result.name).toBe('Bob');
});
it('should preserve readable fields', () => {
const masker = new FieldMasker();
const record = { id: '1', name: 'Carol', secret: 'x' };
const perms = {
name: { readable: true, editable: true },
secret: { readable: false, editable: false },
};
const result = masker.maskResults(record, perms, 'user') as any;
expect(result.name).toBe('Carol');
expect(result.secret).toBeUndefined();
});
it('should return non-editable fields', () => {
const masker = new FieldMasker();
const perms = {
email: { readable: true, editable: false },
name: { readable: true, editable: true },
};
const nonEditable = masker.getNonEditableFields(perms);
expect(nonEditable).toContain('email');
expect(nonEditable).not.toContain('name');
});
it('should strip non-editable fields from write data', () => {
const masker = new FieldMasker();
const data = { name: 'Dave', email: 'dave@example.com', createdAt: '2024' };
const perms = {
email: { readable: true, editable: false },
createdAt: { readable: true, editable: false },
name: { readable: true, editable: true },
};
const result = masker.stripNonEditableFields(data, perms);
expect(result.name).toBe('Dave');
expect(result.email).toBeUndefined();
expect(result.createdAt).toBeUndefined();
});
describe('detectForbiddenWrites', () => {
it('returns [] when no field permissions defined', () => {
const masker = new FieldMasker();
expect(
masker.detectForbiddenWrites({ salary: 9999 }, {}),
).toEqual([]);
});
it('returns [] when all fields are editable', () => {
const masker = new FieldMasker();
const perms = {
salary: { readable: true, editable: true },
};
expect(
masker.detectForbiddenWrites({ salary: 9999 }, perms),
).toEqual([]);
});
it('returns [] when payload only contains fields without permission rules', () => {
const masker = new FieldMasker();
const perms = {
salary: { readable: true, editable: false },
};
// 'name' has no field rule → passes through.
expect(
masker.detectForbiddenWrites({ name: 'Dave' }, perms),
).toEqual([]);
});
it('returns the non-editable fields present in payload (single record)', () => {
const masker = new FieldMasker();
const perms = {
salary: { readable: true, editable: false },
ssn: { readable: false, editable: false },
};
expect(
masker.detectForbiddenWrites(
{ name: 'Dave', salary: 9999, ssn: '...' },
perms,
),
).toEqual(['salary', 'ssn']);
});
it('handles array (bulk insert) — returns union of offenders, deduped, sorted', () => {
const masker = new FieldMasker();
const perms = {
salary: { readable: true, editable: false },
ssn: { readable: false, editable: false },
};
const rows = [
{ name: 'a', salary: 1 },
{ name: 'b', ssn: 'x' },
{ name: 'c', salary: 2, ssn: 'y' },
];
expect(masker.detectForbiddenWrites(rows, perms)).toEqual([
'salary',
'ssn',
]);
});
it('ignores null/non-object rows in a bulk array', () => {
const masker = new FieldMasker();
const perms = { salary: { readable: true, editable: false } };
// null inside array should be skipped, not crash
const rows = [null as any, { salary: 1 }, 'string' as any];
expect(masker.detectForbiddenWrites(rows, perms)).toEqual(['salary']);
});
it('readable-but-not-editable counts as forbidden write (a user who can see a field still cannot change it)', () => {
const masker = new FieldMasker();
const perms = {
approved_by: { readable: true, editable: false },
};
expect(
masker.detectForbiddenWrites({ approved_by: 'u2' }, perms),
).toEqual(['approved_by']);
});
});
});
// ---------------------------------------------------------------------------
// RLSCompiler
// ---------------------------------------------------------------------------
describe('RLSCompiler', () => {
it('should return null for empty policies', () => {
const compiler = new RLSCompiler();
expect(compiler.compileFilter([])).toBeNull();
});
it('should compile equality expression with current_user property', () => {
const compiler = new RLSCompiler();
const policy: any = { object: 'task', operation: 'select', using: 'owner_id = current_user.id' };
const ctx: any = { userId: 'user-42', tenantId: 'tenant-1', roles: [] };
const filter = compiler.compileFilter([policy], ctx);
expect(filter).toEqual({ owner_id: 'user-42' });
});
it('should compile literal equality expression', () => {
const compiler = new RLSCompiler();
const policy: any = { object: 'doc', operation: 'select', using: "status = 'published'" };
const filter = compiler.compileFilter([policy]);
expect(filter).toEqual({ status: 'published' });
});
it('should compile IN expression with array property', () => {
const compiler = new RLSCompiler();
const policy: any = { object: 'project', operation: 'select', using: 'id IN (current_user.roles)' };
const ctx: any = { userId: 'u1', tenantId: 't1', roles: ['role-a', 'role-b'] };
const filter = compiler.compileFilter([policy], ctx);
expect(filter).toEqual({ id: { $in: ['role-a', 'role-b'] } });
});
it('should compile IN expression against pre-resolved org_user_ids', () => {
// Covers the sys_user_org_members policy that lets members see
// fellow collaborators in the active organization. The runtime
// resolver populates ctx.org_user_ids from sys_member; the
// compiler reads it as an arbitrary current_user.* property.
const compiler = new RLSCompiler();
const policy: any = {
object: 'sys_user',
operation: 'select',
using: 'id IN (current_user.org_user_ids)',