-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsecurity-plugin.ts
More file actions
2696 lines (2583 loc) · 134 KB
/
Copy pathsecurity-plugin.ts
File metadata and controls
2696 lines (2583 loc) · 134 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 { Plugin, PluginContext } from '@objectstack/core';
import type { PermissionSet, RowLevelSecurityPolicy } from '@objectstack/spec/security';
import { describeHighPrivilegeBits, describeAnchorForbiddenBits } from '@objectstack/spec/security';
import { MCP_AGENT_PERMISSION_SET_RESTRICTED } from '@objectstack/spec/ai';
import { PermissionEvaluator, crudBucketForOperation } from './permission-evaluator.js';
import { DelegatedAdminGate } from './delegated-admin-gate.js';
import {
explainAccess,
buildContextForUser,
resolveDelegatorContext,
intersectFieldMasks,
} from './explain-engine.js';
import type { ExplainDecision, ExplainOperation } from '@objectstack/spec/security';
import { bootstrapDeclaredPositions } from './bootstrap-declared-positions.js';
import { bootstrapDeclaredPermissions, upsertPackagePermissionSet } from './bootstrap-declared-permissions.js';
import {
createPermissionSetWriteThrough,
registerPermissionSetProjection,
reconcilePermissionSetProjection,
} from './permission-set-projection.js';
import {
syncAudienceBindingSuggestions,
listAudienceBindingSuggestions,
confirmAudienceBindingSuggestion,
dismissAudienceBindingSuggestion,
type SuggestionDeps,
type SuggestionListFilter,
} from './suggested-audience-bindings.js';
import { cleanupPackagePermissions } from './cleanup-package-permissions.js';
import { bootstrapBuiltinRoles } from './bootstrap-builtin-positions.js';
import { bootstrapSystemCapabilities } from './bootstrap-system-capabilities.js';
import { normalizeManagedByVocab } from './normalize-managed-by.js';
import { bootstrapDeclaredCapabilities } from './bootstrap-declared-capabilities.js';
import { RLSCompiler, RLS_DENY_FILTER } from './rls-compiler.js';
import { computeTenantLayer0Filter, andComposeLayers } from './tenant-layer.js';
import { matchesFilterCondition } from '@objectstack/formula';
import { FieldMasker } from './field-masker.js';
import { assertReadableQueryFields } from './predicate-guard.js';
import { PermissionDeniedError } from './errors.js';
import { bootstrapPlatformAdmin } from './bootstrap-platform-admin.js';
import {
backfillOrgAdminGrants,
extractMemberPairs,
reconcileOrgAdminGrant,
} from './auto-org-admin-grant.js';
import { SysPositionDetailPage } from '@objectstack/platform-objects/pages';
import {
securityObjects,
securityDefaultPermissionSets,
securityPluginManifestHeader,
} from './manifest.js';
/**
* [ADR-0095 D3 / Finding 2 / #2937] Platform-admin-EXCLUSIVE capabilities — the
* platform-scoped `systemPermissions` that `admin_full_access` carries and
* `organization_admin` DELIBERATELY withholds (see `default-permission-sets.ts`:
* org admin is granted only `manage_org_users`/`setup.access`/`setup.write`).
*
* Holding ANY of these is the enforcement stand-in for the `PLATFORM_ADMIN`
* posture rung (ADR-0095 D3): it is what distinguishes a true PLATFORM operator
* from a TENANT org admin. Both hold `viewAllRecords`/`modifyAllRecords` via
* their `'*'` wildcard grant, so the superuser-bypass bit ALONE cannot tell them
* apart — which is exactly why an org admin used to cross the Layer 0 tenant wall
* on private/platform-global/better-auth objects (Finding 2). `setup.access`/
* `setup.write` are EXCLUDED on purpose: org admins hold them (they are the Setup
* app shell + tenant-settings-write caps, not platform powers).
*
* NOTE: the fully-correct signal is the `PLATFORM_ADMIN` posture already derived
* in `resolve-authz-context.ts` (`ctx.posture`), but that field is NOT plumbed
* into the ExecutionContext the enforcement middleware receives (the REST/runtime
* transports drop it), so consuming it here would silently no-op. This capability
* probe reads the SAME resolved permission sets enforcement already uses, works on
* every entry point, and — being a strict subset of the old superuser-bit gate —
* can only NARROW the exemption, never widen it (fail-safe).
*/
const PLATFORM_ADMIN_ONLY_CAPABILITIES: readonly string[] = [
'manage_metadata',
'manage_platform_settings',
'studio.access',
'manage_users',
];
/**
* [ADR-0066 D3/⑤] Object `requiredPermissions` normalized into per-CRUD buckets.
* `all` holds capabilities required for EVERY operation (the `string[]` form);
* the per-op buckets hold capabilities from the `{read,create,update,delete}`
* map form. The effective requirement for an operation is `all ∪ <bucket>`.
*/
interface NormalizedRequiredPermissions {
all: string[];
read: string[];
create: string[];
update: string[];
delete: string[];
}
/** Per-object security posture resolved once and cached (see getObjectSecurityMeta). */
interface ObjectSecurityMeta {
isPrivate: boolean;
tenancyDisabled: boolean;
isBetterAuthManaged: boolean;
requiredPermissions: NormalizedRequiredPermissions;
fieldRequiredPermissions: Record<string, string[]>;
}
const EMPTY_REQUIRED_PERMISSIONS: NormalizedRequiredPermissions = Object.freeze({
all: [], read: [], create: [], update: [], delete: [],
}) as NormalizedRequiredPermissions;
/**
* [ADR-0066 / #2918] Provenance spec for the platform/application asset objects
* whose managed rows are write-protected by {@link SecurityPlugin.assertSystemRowWriteGate}.
*
* Both objects share the unified A4 (#2920) `managed_by` vocabulary — a row
* authored by the platform or an application package is not the admin's to
* delete or rewrite:
* • `platform` / `package` are managed; `admin`/∅ (tenant-authored) rows are
* the admin's.
* • sys_position additionally keeps its LEGACY values `system` (→ platform)
* and `config` (→ package) in the managed map: the boot normalizer
* (normalize-managed-by.ts) heals stored rows to the canonical vocabulary,
* but rows written before the normalizer runs — or in a store it has not
* touched yet — must not lose protection in the interim. Dropping the
* legacy keys here is what silently disarmed this gate for sys_position
* after the A4 rename (#2926 ①).
* The map value for each managed `managed_by` is the human owner label used in
* the (business-message-only) deny text.
*/
const SYSTEM_ROW_PROVENANCE: Record<
string,
{ noun: string; pluralNoun: string; managed: Record<string, string> }
> = {
sys_position: {
noun: 'position',
pluralNoun: 'positions',
managed: {
platform: 'the platform',
package: 'an application package',
// Legacy pre-A4 values — keep guarded until every store is normalized.
system: 'the platform',
config: 'an application package',
},
},
sys_capability: {
noun: 'capability',
pluralNoun: 'capabilities',
managed: { platform: 'the platform', package: 'an application package' },
},
};
/** Normalize a raw object `requiredPermissions` (string[] | per-op map) into buckets. */
function normalizeRequiredPermissions(raw: unknown): NormalizedRequiredPermissions {
if (Array.isArray(raw)) {
return { all: raw.map(String), read: [], create: [], update: [], delete: [] };
}
if (raw && typeof raw === 'object') {
const m = raw as Record<string, unknown>;
const bucket = (v: unknown): string[] => (Array.isArray(v) ? v.map(String) : []);
return {
all: [],
read: bucket(m.read),
create: bucket(m.create),
update: bucket(m.update),
delete: bucket(m.delete),
};
}
return { all: [], read: [], create: [], update: [], delete: [] };
}
/**
* [ADR-0066 ⑤] Capabilities required for `operation` = the `all` bucket UNION the
* operation's CRUD bucket. The array form (only `all` populated) thus gates EVERY
* operation exactly as before; the map form gates only the mapped CRUD classes and
* leaves an unmapped custom op ungated. De-duplicated for a clean error message.
*/
function requiredCapsForOperation(
spec: NormalizedRequiredPermissions,
operation: string,
): string[] {
const bucket = crudBucketForOperation(operation);
const caps = bucket ? [...spec.all, ...spec[bucket]] : spec.all;
return caps.length > 0 ? [...new Set(caps)] : [];
}
export interface SecurityPluginOptions {
/**
* Additional permission sets to register with the metadata service on
* plugin start. Defaults to {@link securityDefaultPermissionSets}
* (admin_full_access / member_default / viewer_readonly).
*/
defaultPermissionSets?: PermissionSet[];
/**
* Permission set name applied as an implicit baseline whenever an
* authenticated request has no resolved permission sets (and no positions
* that map to one). This guarantees baseline tenant/owner RLS for
* every logged-in user even before an admin assigns explicit
* profiles. Set to `null` to disable.
*
* @default 'member_default'
*/
fallbackPermissionSet?: string | null;
}
/**
* SecurityPlugin
*
* Provides RBAC, Row-Level Security, and Field-Level Security runtime.
* Registers as an engine middleware on the ObjectQL engine.
*
* This plugin is fully optional — without it, the system operates
* without permission checks (same as current behavior).
*
* **Multi-tenant Organization scoping is provided by the separate
* `@objectstack/organizations` package** (auto-stamps
* `organization_id` on insert, per-org seed replay, default-org
* bootstrap). When that plugin is installed, SecurityPlugin detects
* it via `getService('org-scoping')` and keeps the wildcard
* `current_user.organization_id` RLS policies that ship with the
* default permission sets. Without it, those policies are stripped so
* single-tenant deployments don't pay the field-existence safety-net
* cost on every find.
*
* Dependencies:
* - objectql service (ObjectQL engine with middleware support)
* - metadata service (MetadataFacade for reading permission sets and RLS policies)
*/
/**
* [ADR-0090 D5/D9] Anchor-safety predicates moved to `@objectstack/spec/security`
* (P3) so the authoring linter (`validateSecurityPosture`) and this runtime
* gate share ONE definition. Re-exported here for existing consumers.
*/
export { describeHighPrivilegeBits } from '@objectstack/spec/security';
export class SecurityPlugin implements Plugin {
name = 'com.objectstack.security';
type = 'standard';
version = '1.0.0';
dependencies = ['com.objectstack.engine.objectql'];
private permissionEvaluator = new PermissionEvaluator();
private rlsCompiler = new RLSCompiler();
private fieldMasker = new FieldMasker();
private readonly bootstrapPermissionSets: PermissionSet[];
private readonly fallbackPermissionSet: string | null;
/**
* Runtime probe — set in `start()` from
* `ctx.getService('org-scoping')`. When `false`, wildcard RLS
* policies that reference `current_user.organization_id` are
* stripped from the per-request policy set (saves the
* field-existence safety net cost on every find in single-tenant
* deployments). When `true`, the policies apply normally.
*/
private orgScopingEnabled = false;
/**
* Per-object field-name cache. Populated lazily from the metadata
* service / ObjectQL registry on first access per object. Schemas are
* effectively immutable for the lifetime of the kernel today (hot
* reload tears the kernel down), so we don't bother with
* invalidation — a kernel restart drops the cache.
*/
private readonly fieldNamesCache = new Map<string, Set<string> | null>();
/**
* Per-object cache of tenancy opt-out. `true` means the schema
* explicitly disabled multi-tenancy (`tenancy.enabled === false` or
* `systemFields.tenant === false`). Wildcard policies that target
* the conventional tenant column (`organization_id`) are treated as
* *not applicable* on these tables instead of triggering the
* field-missing deny sentinel — without this, every read of a
* cross-org catalog (e.g. `sys_package`, the Marketplace) returns
* zero rows.
*/
private readonly tenancyDisabledCache = new Map<string, boolean>();
/**
* Service handles captured in `start()` so the request-time RLS resolution
* (used by BOTH the engine middleware and the public {@link getReadFilter}
* service method) shares one code path. `null` until `start()` wires them.
*/
private metadata: any = null;
private ql: any = null;
/** [ADR-0090 D12] Delegated-admin write gate — wired in start() once `ql` exists. */
private delegatedAdminGate: DelegatedAdminGate | null = null;
/**
* [C2 / ADR-0095] Lazy kernel-service resolver, captured in start(). Used by the
* record-grained explain path to reach the optional `sharing` service (a
* deployment without plugin-sharing simply resolves `undefined`). Late-bound so
* plugin load order does not matter.
*/
private resolveKernelService: ((name: string) => any) | null = null;
/** Unsubscribe handle for metadata-change cache invalidation (runtime metadata edits). */
private metadataWatch: { unsubscribe: () => void } | null = null;
/** ADR-0055: cache the resolved master-detail relation per controlled_by_parent object. */
private cbpRelCache = new Map<string, { fk: string; master: string } | null>();
/**
* [ADR-0066 D2/D3] Per-object security posture cache: `private` flag
* (access.default), platform-global flag (tenancy disabled), and the object's
* `requiredPermissions` capability contract. Populated lazily from the schema;
* cleared on metadata change alongside the other schema-derived caches.
*/
private readonly objectSecurityMetaCache = new Map<string, ObjectSecurityMeta>();
private dbLoader?: (names: string[]) => Promise<PermissionSet[]>;
private logger: { info?: (...a: any[]) => void; warn?: (...a: any[]) => void; error?: (...a: any[]) => void } = {};
constructor(options: SecurityPluginOptions = {}) {
this.bootstrapPermissionSets =
options.defaultPermissionSets ?? securityDefaultPermissionSets;
this.fallbackPermissionSet =
options.fallbackPermissionSet === undefined
// ADR-0056 D7: an app may declare its default profile via `isDefault: true`
// on a permission set; it becomes the fallback for users with no explicit
// grants. Falls back to the built-in `member_default` when none is declared.
? (this.bootstrapPermissionSets.find((p) => (p as { isDefault?: boolean }).isDefault)?.name ?? 'member_default')
: options.fallbackPermissionSet;
}
async init(ctx: PluginContext): Promise<void> {
ctx.logger.info('Initializing Security Plugin...');
// Register security services
ctx.registerService('security.permissions', this.permissionEvaluator);
ctx.registerService('security.rls', this.rlsCompiler);
ctx.registerService('security.fieldMasker', this.fieldMasker);
// Bootstrap permission sets (admin_full_access, member_default,
// viewer_readonly by default) — exposed as a service so other
// plugins (e.g. plugin-hono-server's /me/permissions endpoint)
// can pass them as the fallback list to
// `PermissionEvaluator.resolvePermissionSets` without re-importing
// the platform-objects package directly.
ctx.registerService('security.bootstrapPermissionSets', this.bootstrapPermissionSets);
ctx.registerService('security.fallbackPermissionSet', this.fallbackPermissionSet);
ctx.getService<{ register(m: any): void }>('manifest').register({
...securityPluginManifestHeader,
objects: securityObjects,
// [ADR-0090] SDUI detail page for sys_position — Holders (assignments,
// name-keyed junction) + Permission Sets (bindings) as pure
// record:related_list declarations; no bespoke UI.
pages: [SysPositionDetailPage],
// Permission sets ride along on the manifest so the metadata service
// can resolve them by name when SecurityPlugin middleware queries
// `metadata.list('permissions')`.
permissions: this.bootstrapPermissionSets,
// ADR-0029 D7 — contribute the RBAC entries into the Setup app's
// `group_access_control` slot. This plugin owns these objects (K2), so it
// ships their menu too; when the plugin is absent the entries don't appear.
navigationContributions: [
{
app: 'setup',
group: 'group_access_control',
priority: 100,
items: [
{ id: 'nav_positions', type: 'object', label: 'Positions', objectName: 'sys_position', icon: 'shield-check' },
{ id: 'nav_capabilities', type: 'object', label: 'Capabilities', objectName: 'sys_capability', icon: 'badge-check' },
{ id: 'nav_permission_sets', type: 'object', label: 'Permission Sets', objectName: 'sys_permission_set', icon: 'lock' },
],
},
],
});
// ADR-0029 D8 — contribute this plugin's object translations to the i18n
// service on kernel:ready (the i18n plugin may register after this one).
if (typeof (ctx as any).hook === 'function') {
(ctx as any).hook('kernel:ready', async () => {
try {
const i18n = ctx.getService<any>('i18n');
if (i18n && typeof i18n.loadTranslations === 'function') {
const { SecurityTranslations } = await import('./translations/index.js');
for (const [locale, data] of Object.entries(SecurityTranslations)) {
i18n.loadTranslations(locale, data as Record<string, unknown>);
}
}
} catch { /* i18n optional */ }
});
}
ctx.logger.info('Security Plugin initialized', {
defaultPermissionSets: this.bootstrapPermissionSets.map((p) => p.name),
});
}
async start(ctx: PluginContext): Promise<void> {
ctx.logger.info('Starting Security Plugin...');
// Get required services
let ql: any;
let metadata: any;
try {
ql = ctx.getService('objectql');
metadata = ctx.getService('metadata');
} catch (e) {
ctx.logger.warn('ObjectQL or metadata service not available, security middleware not registered');
return;
}
if (!ql || typeof ql.registerMiddleware !== 'function') {
ctx.logger.warn('ObjectQL engine does not support middleware, security middleware not registered');
return;
}
// Capture handles so the request-time RLS resolution is shared by the
// engine middleware AND the public getReadFilter service method.
this.metadata = metadata;
this.ql = ql;
this.logger = ctx.logger;
this.rlsCompiler.setLogger?.(ctx.logger);
// [C2 / ADR-0095] Late-bound resolver for the optional `sharing` service.
this.resolveKernelService = (name: string) => {
try { return ctx.getService(name); } catch { return undefined; }
};
// Invalidate metadata-derived caches when object/field metadata changes
// at runtime (Studio / AI authoring). Without this they go stale until
// restart — even single-node. With a cluster pub/sub driver the
// metadata.changed event propagates cross-node, so peers invalidate too.
const md: any = this.metadata;
if (typeof md?.watch === 'function') {
this.metadataWatch = md.watch('*', () => {
this.fieldNamesCache.clear();
this.tenancyDisabledCache.clear();
this.cbpRelCache.clear();
this.objectSecurityMetaCache.clear();
});
}
// Probe whether org-scoping (auto-stamp + tenant RLS) is active. We capture
// the boolean once at start time (plugin DI graph is static after start)
// and let `collectRLSPolicies` consult it on every request.
//
// ADR-0093 D4 — prefer the `tenancy` service, the single source of truth.
// It derives `isolationActive` from the very same `org-scoping` presence
// probe, so this is behavior-identical while centralizing the fact. Fall
// back to probing `org-scoping` directly when the tenancy service isn't
// wired (e.g. an embedding without plugin-auth), preserving prior behavior.
try {
const tenancy = ctx.getService<{ isolationActive?: boolean }>('tenancy');
this.orgScopingEnabled = !!tenancy?.isolationActive;
} catch {
try {
this.orgScopingEnabled = !!ctx.getService('org-scoping');
} catch {
this.orgScopingEnabled = false;
}
}
if (this.orgScopingEnabled) {
ctx.logger.info(
'[security] org-scoping plugin detected — wildcard `organization_id` RLS policies will apply',
);
} else {
ctx.logger.info(
'[security] org-scoping plugin not present — wildcard `organization_id` RLS policies will be stripped (single-tenant mode)',
);
}
// Construct a dbLoader once that lets resolvePermissionSets
// surface user-defined permission sets from `sys_permission_set`
// (created via the admin UI) in addition to plugin-registered
// ones. Uses `isSystem` to bypass tenant RLS.
const dbLoader = ql
? async (names: string[]) => {
let rows: any;
try {
rows = await ql.find(
'sys_permission_set',
{ where: { name: { $in: names } }, limit: names.length },
{ context: { isSystem: true } },
);
} catch {
rows = [];
}
const list = Array.isArray(rows) ? rows : rows?.records ?? [];
const parseJson = (v: any, fallback: any) => {
if (typeof v !== 'string') return v ?? fallback;
try { return JSON.parse(v || JSON.stringify(fallback)); } catch { return fallback; }
};
return list.map((r: any) => ({
name: r.name,
label: r.label,
objects: parseJson(r.object_permissions, {}),
fields: parseJson(r.field_permissions, {}),
systemPermissions: parseJson(r.system_permissions, []),
// [ADR-0090 D12] Hydrate the delegated-admin scope so the gate can
// resolve a DB-authored delegate's authority. Null column → absent.
...(r.admin_scope ? { adminScope: parseJson(r.admin_scope, undefined) } : {}),
}));
}
: undefined;
this.dbLoader = dbLoader;
// [ADR-0090 D12] Delegated-admin gate shares the SAME permission-set
// resolution as the CRUD middleware, so a delegate's authority and their
// ordinary grants can never drift. (`ql` is guaranteed non-null here —
// start() bailed out above without a middleware-capable engine.)
this.delegatedAdminGate = new DelegatedAdminGate({
ql,
resolveSets: (context: any) => this.resolvePermissionSetsForContext(context),
logger: ctx.logger,
});
// ADR-0021 D-C — expose the per-request READ scope as a reusable service.
// The analytics raw-SQL path (which bypasses this engine middleware)
// auto-bridges to `getService('security').getReadFilter(object, context)`
// to enforce tenant/RLS on every base + joined object. We register the
// service only once the metadata/ql/dbLoader handles are wired (above), so
// a degraded start never exposes a half-initialised resolver.
try {
// [ADR-0090 D5/D9] Suggested audience bindings — shared deps for the
// list/confirm/dismiss surface (same set resolution as the middleware
// and the delegated-admin gate, so admin-ness can never drift).
const suggestionDeps: SuggestionDeps = {
ql,
metadata,
resolveSets: (context: any) => this.resolvePermissionSetsForContext(context),
logger: ctx.logger,
};
ctx.registerService('security', {
getReadFilter: (object: string, context?: any) => this.getReadFilter(object, context),
// [ADR-0046 §6.7] Effective permission-set NAMES for a caller — the
// primitive the REST read layer needs to evaluate a permission-set-
// gated book/doc audience ({ permissionSet: '…' }). Same resolution
// as the middleware (positions expanded, additive baseline), so the
// docs gate can never drift from data-plane enforcement. Throws on
// resolution failure — callers must fail CLOSED (ADR-0049).
resolvePermissionSetNames: async (context?: any): Promise<string[]> => {
const sets = await this.resolvePermissionSetsForContext(context);
return sets.map((s) => s.name);
},
// [ADR-0090 D6] First-class access explanation. Same code paths as
// the middleware (resolution/evaluator/RLS compiler) — explained by
// construction. Explaining ANOTHER user requires `manage_users`.
explain: (request: { object: string; operation: string; userId?: string }, callerContext?: any) =>
this.explainAccessForCaller(request, callerContext),
// [ADR-0090 D5/D9] Install-time suggestion surface: packages suggest
// audience-anchor bindings; a tenant admin confirms (the binding is
// written under the anchor + delegated-admin gates) or dismisses.
listAudienceBindingSuggestions: (callerContext?: any, filter?: SuggestionListFilter) =>
listAudienceBindingSuggestions(suggestionDeps, callerContext, filter),
confirmAudienceBindingSuggestion: (callerContext: any, id: string) =>
confirmAudienceBindingSuggestion(suggestionDeps, callerContext, id),
dismissAudienceBindingSuggestion: (callerContext: any, id: string) =>
dismissAudienceBindingSuggestion(suggestionDeps, callerContext, id),
});
ctx.logger.info('[security] registered "security" service (getReadFilter, explain, audience-binding suggestions) — ADR-0021 D-C / ADR-0090 D5/D6/D9');
} catch (e) {
ctx.logger.warn?.('[security] failed to register "security" service', {
error: (e as Error).message,
});
}
// Register security middleware
ql.registerMiddleware(async (opCtx: any, next: () => Promise<void>) => {
// System operations bypass security
if (opCtx.context?.isSystem) {
return next();
}
// ADR-0056 (Option A) — declaration-derived PUBLIC-FORM grant. A public
// form submission carries `publicFormGrant: { object }` derived from the
// form's declared target (set by the rest-server form-submit route). It
// authorizes ONLY create + the immediate read-back on THAT object — never
// anything else, and never the anonymous fall-open. This lets public forms
// work under secure-by-default (requireAuth) WITHOUT a deployment-configured
// `guest_portal`, scoped to exactly the declared object (the field
// allow-list is enforced at the route; the context is request-scoped).
const formGrant = opCtx.context?.publicFormGrant;
if (formGrant && typeof formGrant === 'object' && (formGrant as { object?: string }).object) {
const grantObject = (formGrant as { object: string }).object;
const allowed =
opCtx.object === grantObject &&
['insert', 'find', 'findOne', 'count'].includes(opCtx.operation);
if (allowed) return next();
throw new PermissionDeniedError(
`[Security] Access denied: public-form grant permits only create/read-back on '${grantObject}', ` +
`not '${opCtx.operation}' on '${opCtx.object}'`,
{ operation: opCtx.operation, object: opCtx.object },
);
}
// [ADR-0086 P2 — 块2, evolved by ADR-0094] Two-doors write gate. A
// permission set stamped `managed_by:'package'` is owned by the PACKAGE
// door: its BASELINE is authored in the package and lands via publish
// (块1). The admin door must never FORGE that provenance (insert or
// update), and the lifecycle ops with no overlay translation
// (transfer/restore/purge) stay refused on package rows. Ordinary
// `update`/`delete` on a package row are handled downstream by the
// ADR-0094 write-through, which translates them into env-scope OVERLAY
// operations (customize / reset via the standard ADR-0005 layering) —
// the boot re-seed can no longer revert an admin's change, because the
// change lives in the overlay and the record projects overlay-wins.
// Placed BEFORE the empty-principal fall-open and the CRUD check so the
// forging boundary holds even for a principal-less context and a
// superuser with modifyAllRecords. System/boot writes carry `isSystem`
// and already short-circuited the whole middleware above.
await this.assertPackageManagedWriteGate(opCtx);
// [ADR-0066 / #2918] Built-in row-write guardrail for the platform/app
// ASSET objects sys_position / sys_capability. Like the package gate
// above, an unconditional data-layer boundary: a row authored by the
// platform or an application package (provenance recorded in
// `managed_by`) may not be deleted or rewritten through the admin door.
// Unlike sys_permission_set there is NO ADR-0094 overlay write-through
// for these objects, so the refusal must hold for update/delete here
// rather than deferring to a downstream translation. Runs BEFORE the
// empty-principal fall-open and the CRUD check so the boundary holds even
// for a principal-less context and a superuser with modifyAllRecords.
// System/boot writes carry `isSystem` and already short-circuited above,
// so the seeder and package publish are unaffected.
await this.assertSystemRowWriteGate(opCtx);
// [ADR-0090 D5/D9] Audience-anchor binding guard — like the package
// gate above, an unconditional data-layer boundary: a permission set
// carrying high-privilege bits must never be bound to the `everyone`
// or `guest` positions, no matter who asks. (Boot/system writes carry
// `isSystem` and short-circuited above; the dev-mode default binding
// is validated at seed time by the same predicate.)
await this.assertAudienceAnchorBindingGate(opCtx);
// [ADR-0090 D12] Delegated-administration gate. Writes to the RBAC
// link tables (assignments / bindings / direct grants / env-set
// authoring) are a GOVERNED operation: tenant-level admins pass
// through to the ordinary CRUD/RLS checks; delegates need a covering
// adminScope (BU subtree + allowlist + strict containment); everyone
// else — including holders of plain CRUD grants on these tables — is
// denied. Runs BEFORE the empty-principal fall-open below so RBAC
// tables fail CLOSED for principal-less non-system contexts.
if (this.delegatedAdminGate) {
await this.delegatedAdminGate.assert(opCtx);
}
const positions = opCtx.context?.positions ?? [];
const explicitPermissionSets = opCtx.context?.permissions ?? [];
// Skip security checks if no positions AND no explicit permission sets
// AND no userId (anonymous/unauthenticated). The auth middleware
// should handle authentication separately.
if (
positions.length === 0 &&
explicitPermissionSets.length === 0 &&
!opCtx.context?.userId
) {
return next();
}
// 1. Resolve permission sets from BOTH role names and explicit
// permission set names attached to the execution context. The
// resolution (incl. the implicit + post-resolution baseline
// fallback) is shared with the public getReadFilter service via
// resolvePermissionSetsForContext — keeping the find-path RLS and
// the analytics raw-SQL RLS provably in lock-step.
let permissionSets: PermissionSet[] = [];
try {
permissionSets = await this.resolvePermissionSetsForContext(opCtx.context);
} catch (e) {
// Fail CLOSED. A permission-resolution failure must DENY the request,
// never bypass the checks (that would let a degraded metadata service
// expose every tenant's data). System/bootstrap operations already
// short-circuited above (`opCtx.context?.isSystem`), so reaching here
// means an authenticated user request whose RBAC/RLS could not be
// resolved — deny it and alert.
ctx.logger.error(
`[security] permission resolution failed for operation '${opCtx.operation}' on ` +
`object '${opCtx.object}' (user ${opCtx.context?.userId ?? 'unknown'}) — ` +
`denying request (fail-closed)`,
e instanceof Error ? e : new Error(String(e)),
);
throw new PermissionDeniedError(
`[Security] Access denied: permission subsystem unavailable for ` +
`operation '${opCtx.operation}' on object '${opCtx.object}'`,
);
}
// [ADR-0090 D10 — agent intersection] When this principal acts ON BEHALF
// OF a user (an AI agent or a service), its effective permission is the
// INTERSECTION of its own grants and the delegator's grants — never the
// union (confused-deputy prevention). Resolve the delegator's effective
// permission sets ONCE here; every gate below AND-composes the two lists
// so the tighter of the two wins at each axis (CRUD, capabilities, FLS,
// depth, row-level using/check, VAMA). The whole thing is gated on the
// presence of the delegation LINK (not the `principalKind` label — a
// service acting for a user is the identical risk): on the ordinary
// non-delegated path `delegatorSets` stays null, every combine reduces to
// today's expression, no extra `ql` read happens, and behaviour is
// byte-identical. A dangling link (delegator deleted) fails CLOSED — see
// resolveDelegatorContext for why "empty sets" would be wrong (the
// additive baseline would resurrect access for a non-existent user).
let delegatorSets: PermissionSet[] | null = null;
let delegatorContext: any = null;
if (permissionSets.length > 0 && opCtx.context?.onBehalfOf?.userId) {
const del = await resolveDelegatorContext(this.ql, opCtx.context);
if (del.kind === 'missing') {
throw new PermissionDeniedError(
`[Security] Access denied: on-behalf-of principal names delegator ` +
`'${del.userId}', who does not exist — refusing to act (ADR-0090 D10 fail-closed)`,
{ operation: opCtx.operation, object: opCtx.object },
);
}
if (del.kind === 'resolved') {
delegatorContext = del.context;
delegatorSets = await this.resolvePermissionSetsForContext(delegatorContext);
}
}
// [ADR-0066 D2/D3] Resolve the object's security posture (private flag,
// platform-global flag, capability contract) once for the checks below.
const secMeta =
permissionSets.length > 0
? await this.getObjectSecurityMeta(opCtx.object)
: { isPrivate: false, tenancyDisabled: false, isBetterAuthManaged: false, requiredPermissions: EMPTY_REQUIRED_PERMISSIONS, fieldRequiredPermissions: {} as Record<string, string[]> };
// [#2850] $expand sub-read gate relaxation. The engine's expand path
// re-enters `find` for a referenced object carrying `__expandRead` (a
// server-set marker; `executionContext` is never client-built). For a
// PUBLIC referenced object — covered by the '*' wildcard grant and thus
// already broadly readable — applying the object-level CRUD /
// requiredPermissions gate to the EXPANSION would only surface "never
// designed for expand" modeling gaps (over-blocking a legitimate
// status/owner lookup) without adding protection, since the row is
// already visible. So waive those two throw-gates for PUBLIC expand
// sub-reads only. RLS injection (step 3) and FLS masking (step 4) still
// run, and a PRIVATE referenced object keeps the FULL gate — expansion
// may reveal only rows the caller could have read directly.
const expandSkipCrud =
opCtx.operation === 'find' &&
opCtx.context?.__expandRead === true &&
!secMeta.isPrivate;
// 1.5. [ADR-0066 D3/⑤] requiredPermissions AND-gate — a capability
// prerequisite checked BEFORE the CRUD grant (ADR §Precedence): a
// caller missing any required capability is denied regardless of how
// permissive their grants are. Per-operation (⑤): only the caps for
// THIS operation's CRUD class (plus any all-operations caps) apply.
if (permissionSets.length > 0 && !expandSkipCrud) {
const required = requiredCapsForOperation(secMeta.requiredPermissions, opCtx.operation);
if (required.length > 0) {
const held = this.permissionEvaluator.getSystemPermissions(permissionSets);
const missing = required.filter((cap) => !held.has(cap));
// [ADR-0090 D10] Both principals must hold every required capability.
const missingDel = delegatorSets
? required.filter((cap) => !this.permissionEvaluator.getSystemPermissions(delegatorSets!).has(cap))
: [];
if (missing.length > 0 || missingDel.length > 0) {
const allMissing = [...new Set([...missing, ...missingDel])];
throw new PermissionDeniedError(
`[Security] Access denied: '${opCtx.object}' (operation '${opCtx.operation}') requires capability ` +
`[${required.join(', ')}] — ${missing.length > 0 ? 'caller' : 'the delegator'} is missing [${allMissing.join(', ')}]`,
{
operation: opCtx.operation,
object: opCtx.object,
positions,
permissionSets: explicitPermissionSets,
requiredPermissions: required,
missingPermissions: allMissing,
},
);
}
}
}
// 2. CRUD permission check
if (permissionSets.length > 0 && !expandSkipCrud) {
const allowed = this.permissionEvaluator.checkObjectPermission(
opCtx.operation,
opCtx.object,
permissionSets,
{ isPrivate: secMeta.isPrivate },
);
if (!allowed) {
throw new PermissionDeniedError(
`[Security] Access denied: operation '${opCtx.operation}' on object '${opCtx.object}' ` +
`is not permitted for positions [${positions.join(', ')}]`,
{ operation: opCtx.operation, object: opCtx.object, positions, permissionSets: explicitPermissionSets },
);
}
// [ADR-0090 D10] The delegator must independently grant the same op — an
// agent may never act beyond the reach of the user it stands in for.
if (delegatorSets && !this.permissionEvaluator.checkObjectPermission(
opCtx.operation,
opCtx.object,
delegatorSets,
{ isPrivate: secMeta.isPrivate },
)) {
throw new PermissionDeniedError(
`[Security] Access denied: on-behalf-of principal may not '${opCtx.operation}' ` +
`'${opCtx.object}' — the delegator lacks that grant (ADR-0090 D10 intersection)`,
{ operation: opCtx.operation, object: opCtx.object, positions, permissionSets: explicitPermissionSets },
);
}
}
// 2.6. [ADR-0057 D1] Stash the grant's access DEPTH for this object so the
// sharing service can widen the owner-match (owner_id IN unit-set)
// while still OR-ing in shares. Owner-set expansion needs the BU graph
// (plugin-sharing), so we pass the scope STRING, not the resolved set.
if (permissionSets.length > 0) {
const sc: any = opCtx.context;
// The AGENT's own depth drives plugin-sharing's owner-match for the
// agent identity (unchanged on the non-delegated path).
if (['find', 'findOne', 'count', 'aggregate'].includes(opCtx.operation)) {
sc.__readScope = this.permissionEvaluator.getEffectiveScope('read', opCtx.object, permissionSets, { isPrivate: secMeta.isPrivate });
// [ADR-0090 D10] Stash the DELEGATOR's own read depth SEPARATELY (not a
// min of the two). The OWD/sharing owner-match is identity-scoped:
// plugin-sharing re-runs the owner filter under the delegator's
// identity + THIS depth and AND-s it in, giving a true per-identity
// intersection. Narrowing __readScope alone would wrongly scope the
// AGENT's identity to the delegator's depth (owner_id = agentId),
// hiding the very rows the delegator legitimately owns.
if (delegatorSets) {
sc.__delegatorReadScope = this.permissionEvaluator.getEffectiveScope('read', opCtx.object, delegatorSets, { isPrivate: secMeta.isPrivate });
}
} else if (['update', 'delete', 'transfer', 'restore', 'purge'].includes(opCtx.operation)) {
sc.__writeScope = this.permissionEvaluator.getEffectiveScope('write', opCtx.object, permissionSets, { isPrivate: secMeta.isPrivate });
if (delegatorSets) {
sc.__delegatorWriteScope = this.permissionEvaluator.getEffectiveScope('write', opCtx.object, delegatorSets, { isPrivate: secMeta.isPrivate });
}
}
}
// 2.7. Row-level WRITE authorization (pre-image check).
//
// RLS is injected as a `where` filter on the read path (step 3, via
// `opCtx.ast`), but a single-id update/delete goes straight to
// `driver.update(object, id, …)` / `driver.delete(object, id)` — it builds
// no `ast`, so the row-level predicate is NEVER applied to by-id writes.
// The result (#1985): the CRUD check passes (member_default grants edit/
// delete) and the owner/tenant RLS that was supposed to scope the write is
// silently bypassed — any member could modify another user's record.
//
// Fix: before the mutation, compute the write-operation RLS filter and
// verify the TARGET row satisfies it. We re-read the row through the
// engine with `{ id } AND <writeFilter>`; a `find` does not re-enter this
// block, so there is no recursion, and read-side RLS/tenant scoping
// compose naturally. A `null` result means the row is either gone or
// RLS-hidden → deny. When `computeRlsFilter` returns `null` (no policy
// applies — e.g. an admin set with no RLS, or `modifyAllRecords`) the
// check is skipped and behaviour is unchanged.
if (
// update/delete today; transfer/restore/purge are pre-wired (#1883) so
// the M2 ops inherit the pre-image check the moment they dispatch —
// the CRUD bit alone must never be the only row-level defense.
['update', 'delete', 'transfer', 'restore', 'purge'].includes(opCtx.operation) &&
permissionSets.length > 0 &&
!!opCtx.context?.userId &&
this.ql
) {
const targetId = this.extractSingleId(opCtx);
if (targetId != null) {
// RLS policies declare select/insert/update/delete — map the
// destructive lifecycle class onto its nearest write class so
// authored policies apply (purge destroys like delete;
// transfer/restore mutate like update).
const rlsOperation =
opCtx.operation === 'purge' ? 'delete'
: opCtx.operation === 'transfer' || opCtx.operation === 'restore' ? 'update'
: opCtx.operation;
const writeFilter = await this.computeRlsFilter(
permissionSets,
opCtx.object,
rlsOperation,
opCtx.context,
);
// [ADR-0090 D10] The target row must satisfy BOTH principals' write
// RLS — a by-id write on behalf of a user may only touch rows that
// user could also touch. Compute the delegator's write filter against
// the delegator's context (its userId/tenant substitutions) and AND
// it into the same pre-image re-read.
const delWriteFilter = delegatorSets
? await this.computeRlsFilter(delegatorSets, opCtx.object, rlsOperation, delegatorContext)
: null;
const writeParts = [writeFilter, delWriteFilter].filter(Boolean) as Record<string, unknown>[];
if (writeParts.length > 0) {
let visible: unknown = null;
try {
visible = await this.ql.findOne(opCtx.object, {
where: { $and: [{ id: targetId }, ...writeParts] },
context: opCtx.context,
});
} catch {
// A read denial (e.g. no read permission) is itself a "cannot
// touch this row" signal — fall through to the deny below.
visible = null;
}
if (!visible) {
throw new PermissionDeniedError(
`[Security] Access denied: not permitted to ${opCtx.operation} this ` +
`'${opCtx.object}' record (row-level security)`,
{
operation: opCtx.operation,
object: opCtx.object,
positions,
permissionSets: explicitPermissionSets,
recordId: targetId,
},
);
}
}
}
}
// 2.8. ADR-0055 — controlled-by-parent WRITE: a detail write (insert/update/
// delete) requires edit access to its master. The detail itself carries no
// authored RLS, so the #1994 pre-image check above is a no-op for it; this
// closes the by-id write path by checking the master instead.
if (
['insert', 'update', 'delete', 'transfer', 'restore', 'purge'].includes(opCtx.operation) &&
permissionSets.length > 0 &&
!!opCtx.context?.userId &&
this.ql
) {
await this.assertControlledByParentWrite(
permissionSets,
opCtx.object,
opCtx.operation,
opCtx,
opCtx.context,
);
// [ADR-0090 D10] The delegator must ALSO have edit access to the master
// — a detail write on behalf of a user requires that user's master-edit.
if (delegatorSets) {
await this.assertControlledByParentWrite(
delegatorSets,
opCtx.object,
opCtx.operation,
opCtx,
delegatorContext,
);
}
}
// 2.5. Field-Level Security write enforcement.
//
// The client-side masker (ObjectForm / inline grid) already hides
// non-editable fields from the UI, but that is a UX layer only —
// a hand-crafted POST / direct ObjectQL call can still target a
// forbidden field. We fail-closed here with an explicit 403 and
// the offending field names, so:
//
// - honest clients get an actionable error (vs. silent drop,
// which manifests as a confusing partial-save), and
// - probing clients see that the boundary is enforced (vs.
// getting a 200 with the field silently ignored, which
// reveals nothing).
//
// Runs BEFORE the tenant/owner auto-injection (step 3.5) so the
// system-set fields are not subject to the user's edit
// permissions — they are populated from the execution context,
// not from the caller's payload.
if (
(opCtx.operation === 'insert' || opCtx.operation === 'update') &&
opCtx.data &&
permissionSets.length > 0
) {
let fieldPerms = this.permissionEvaluator.getFieldPermissions(
opCtx.object,
permissionSets,
);
// [ADR-0066 D3] AND-gate field-level requiredPermissions into the map.
fieldPerms = this.foldFieldRequiredPermissions(fieldPerms, secMeta.fieldRequiredPermissions, permissionSets);
// [ADR-0090 D10] Intersect with the delegator's field perms — a field
// the agent may edit but the delegator may not becomes forbidden.
if (delegatorSets) {
let delFieldPerms = this.permissionEvaluator.getFieldPermissions(opCtx.object, delegatorSets);
delFieldPerms = this.foldFieldRequiredPermissions(delFieldPerms, secMeta.fieldRequiredPermissions, delegatorSets);
fieldPerms = intersectFieldMasks(fieldPerms, delFieldPerms);
}
if (Object.keys(fieldPerms).length > 0) {
const forbidden = this.fieldMasker.detectForbiddenWrites(
opCtx.data,
fieldPerms,
);
if (forbidden.length > 0) {
throw new PermissionDeniedError(
`[Security] Field write denied: not permitted to edit ` +
`[${forbidden.join(', ')}] on '${opCtx.object}'`,
{
operation: opCtx.operation,
object: opCtx.object,
positions,
permissionSets: explicitPermissionSets,
forbiddenFields: forbidden,
},
);
}
}
}
// 2.5b. Field-Level Security READ enforcement for aggregate inputs.
//
// The read path relies on RESULT masking (step 4) to hide FLS-protected
// fields, but step 4 only covers find/findOne/insert/update — and an
// aggregate's output rows carry only aliases, so masking could never
// recover which source field fed `sum(salary) AS total`. Without an
// input-side gate a caller may read a protected field's statistics
// (sum/avg/min/max reveal the value outright on a single-row group).
// Enforce on the INPUT: any groupBy / aggregation reference to an
// FLS-unreadable field is rejected fail-closed with the offending names
// (mirrors the write gate in 2.5). `where`-filter probing is a
// platform-wide class shared with find() and is not widened here.