Repository navigation
Expand file tree
/
Copy pathsharing-plugin.ts
More file actions
1914 lines (1850 loc) · 100 KB
/
Copy pathsharing-plugin.ts
File metadata and controls
1914 lines (1850 loc) · 100 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 type { Plugin, PluginContext } from '@objectstack/core';
import {
resolveAuthzContext,
isAuthzStoreUnavailableError,
// [#16013] The ADMISSION posture read is ONE call now: the shared
// classification owns #13906 decision 1 option A (branded "never registered"
// stays quiet, every other rejection is the ADR-0112 outage) and reads the
// posture IN FORCE off the `tenancy` service (ADR-0093 D4/D5: a deployment
// that REQUESTS `isolated` without the `@objectstack/organizations` runtime is
// `single` in force). What stays HERE is the wiring fact -- see
// `resolveAdmissionTenancyPosture` for why this seam's quiet answer is its
// own argument and not the helper's.
classifyAdmissionTenancyPosture,
type TenancyPostureSource,
// [ADR-0069 · #23287] The auth service's per-user posture computation, bound
// for the shared key-admission seam; the posture the resolver decides rides
// the envelope the share-link door reads (`ExecutionContext.authGate`).
userAuthGateSourceOf,
// [#23367] The API-key lifecycle policy source, and its branded refusal.
apiKeyLifecyclePolicySourceOf,
isApiKeyLifecycleRefusalError,
type RequestAuthService,
// [#30237] A write's class (purge → delete, restore/transfer → update): the
// one mapping plugin-security's write gates read too.
rlsOperationForVerb,
credentialUseClientFor,
} from '@objectstack/core';
import type { EngineMiddleware, OperationContext } from '@objectstack/objectql';
import { resolveEngineDeleteDispatch, resolveEngineUpdateDispatch } from '@objectstack/objectql';
import type {
AuthSessionApi,
IAuthService,
IHierarchyScopeResolver,
IHttpRequest,
IHttpServer,
II18nService,
IMetadataService,
IObjectQLEngine,
} from '@objectstack/spec/contracts';
import { OWNERSHIP_QUEUE_SERVICE } from '@objectstack/spec/contracts';
// [commit 8e13ca876] The share-link routes' context is the FULL authorization envelope —
// it feeds enforcement (`engine.find`), so it is an `ExecutionContext`, never
// the route-local `ShareLinkExecutionContext`.
import type { ExecutionContext } from '@objectstack/spec/kernel';
// [#8430, extending #8220] The ONE filter-subtree provenance mechanism. This
// middleware is a read-scope merge boundary and stamps the same spec-declared
// mark `plugin-security` and `service-analytics` stamp at theirs — never a
// local flag, never a second spelling of the same idea.
import { markFilterSubtreeProvenance } from '@objectstack/spec/data';
// [#12260] The SANCTIONED renderer for OPERATION-level refusal copy. The
// Operation Message Catalog is the ONE seat for these sentences — its own
// header bars both a package-local string table and a second rendering
// mechanism for a second producer, and commit aa5994e17 landed this middleware's key
// (`record_write_denied`) into it ahead of this consumer half.
import { renderOperationMessage, type ValidationMessageTranslator } from '@objectstack/spec/system';
import {
SysRecordShare,
SysSharingRule,
SysShareLink,
SysQueue,
SysQueueMember,
SysAssignmentCursor,
SysAssignmentRule,
} from './objects/index.js';
import { SysQueueDetailPage } from './sys-queue.page.js';
import { OwnershipQueueService, specsReadBusinessUnits, type OwnershipQueueEngine } from './ownership-queue-service.js';
import { bindQueueGuards, bindQueueRecipientRecompute, reportShadowedAuthoredQueues } from './queue-hooks.js';
import { bindAssignmentRuleGuards, reportShadowedAuthoredAssignmentRules } from './assignment-rule-hooks.js';
import { SysBusinessUnit, SysBusinessUnitMember } from '@objectstack/platform-objects/identity';
import {
SharingService,
type SharingEngine,
type SharingApprovalReadProbe,
type SharingSecurityProbe,
type SharingTenancyProbe,
} from './sharing-service.js';
import { SharingRuleService, bindDeclaredRuleNameGuard, bindSharingRuleActivationReconcile } from './sharing-rule-service.js';
import { ShareLinkService } from './share-link-service.js';
import { registerShareLinkRoutes } from './share-link-routes.js';
import { SHAREABLE_OBJECTS_ROUTE, registerShareableObjectsRoutes } from './shareable-objects-routes.js';
import { SharingRulesNotRunningError } from './shareable-objects.js';
import {
rebindRuleHooks,
bindRuleCriteriaGuard,
bindRuleObjectEnforcementGuard,
bindRuleRecipientGuard,
RULE_REBIND_TRIGGER_PACKAGE,
} from './rule-hooks.js';
import { bindRuleProvenanceStamp, unbindRuleProvenanceStamp } from './sharing-rule-provenance.js';
import { bindPrimaryBuHooks, backfillPrimaryBu } from './primary-bu-projection.js';
import { bindBusinessUnitTreeRecompute } from './bu-tree-recompute.js';
import { bindRecipientMembershipRecompute } from './recipient-membership-recompute.js';
import { bindRecordShareCascade } from './record-share-cascade.js';
import { createDeclaredSharingRuleSource } from './declared-sharing-rules.js';
import { normalizeTenancyPosture, postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/security';
import { inProcessSessionReadInput } from '@objectstack/types';
import type { ShareLinkLabelProtocol } from '@objectstack/types';
import { backfillStoredDeclarationPackagesAtBoot } from './stored-declaration-package-backfill.js';
import { registeredObjectNames, reportInertShareGrantHolders, shareGrantRegistrationRefusal } from './share-arm-boot.js';
/**
* One page of the boot's organization enumeration. A PAGE size, not a cap: the
* walk reads until a short page, so every organization is served — an
* organization left out of the scopes would not only go unserved, the boot's
* orphaned-grant sweep would revoke its declared rules' grants.
*/
const DECLARED_RULE_ORGANIZATION_PAGE = 500;
/**
* [ADR-0131 D2] The scopes declared sharing rules are served in
* (`SharingRuleService.setDeclaredRuleScopes`): exactly one organization-less
* scope under `single`, and under a wall EVERY organization, read by a keyset
* walk on `id` until a short page — short as READ, never as kept: a page that
* came back full is followed, whatever it held. These are the passes the
* retired seeder made, as reads (#10103).
*
* `null` when the enumeration failed at any page, or a page answered a row
* whose `id` the walk cannot read: an unreadable `sys_organization` means "we
* do not know", never "there are no tenants" — and never a partial list,
* because the scopes decide which name-keyed grants the boot sweep keeps. The
* caller marks the scopes UNKNOWN
* (`SharingRuleService.setDeclaredRuleScopesUnknown`): no declared rule is
* served, and no declared rule's grant is revoked.
*/
export async function resolveDeclaredRuleScopes(
engine: any,
posture: TenancyPosture,
logger?: { warn?: (m: string, meta?: any) => void },
): Promise<Array<string | null> | null> {
if (!postureEnforcesWall(posture)) return [null];
const ids: string[] = [];
let after: string | undefined;
for (;;) {
let rows: any;
try {
rows = await engine.find('sys_organization', {
...(after === undefined ? {} : { where: { id: { $gt: after } } }),
fields: ['id'],
orderBy: [{ field: 'id', order: 'asc' }],
limit: DECLARED_RULE_ORGANIZATION_PAGE,
context: { isSystem: true },
});
} catch (e: any) {
logger?.warn?.('SharingServicePlugin: could not enumerate organizations — declared sharing rules ' +
'are served in NO organization until the next boot, and no declared rule\'s grant is revoked ' +
'meanwhile (the standing grants keep answering). Remedy: restore read access to sys_organization ' +
'and restart.', { error: e?.message, read: ids.length });
return null;
}
const read: any[] = Array.isArray(rows) ? rows : [];
const page = read
.map((r: any) => r?.id)
.filter((id: unknown): id is string => typeof id === 'string' && id !== '');
// A row without a readable id is a failed read, not a shorter page: judged
// on the kept ids, a full page holding one would end the walk early and
// answer the partial list this function never answers.
if (page.length !== read.length) {
logger?.warn?.('SharingServicePlugin: sys_organization answered a row with no readable id — declared ' +
'sharing rules are served in NO organization until the next boot, and no declared rule\'s grant is ' +
'revoked meanwhile (the standing grants keep answering). Remedy: give every sys_organization row ' +
'its id and restart.', { read: ids.length });
return null;
}
ids.push(...page);
if (read.length < DECLARED_RULE_ORGANIZATION_PAGE) return ids;
after = page[page.length - 1];
}
}
/**
* The id of the organization a `sys_organization` insert just created. Read
* from the write's result first and its input second, because an insert that
* lets the engine mint the id carries none on the way in. Returns `undefined`
* rather than guessing — the caller refuses to serve declared rules
* organization-less on a walled deployment, which is the point.
*/
function createdOrganizationId(opCtx: any): string | undefined {
const candidates = [
opCtx?.result?.id,
Array.isArray(opCtx?.result) ? opCtx.result[0]?.id : undefined,
opCtx?.data?.id,
opCtx?.doc?.id,
opCtx?.record?.id,
opCtx?.id,
];
for (const c of candidates) {
if (typeof c === 'string' && c !== '') return c;
}
return undefined;
}
export interface SharingPluginOptions {
/** Extra object names that bypass sharing entirely. */
bypassObjects?: string[];
/**
* Disable enforcement (read filter + canEdit) while still registering
* the schema + service. Useful in development to flip enforcement on
* via env var without rebuilding.
*/
enforce?: boolean;
/**
* Disable the public share-link REST routes. The `IShareLinkService`
* is always registered (other services may depend on it); only the
* HTTP surface is suppressed.
*/
registerShareLinkRoutes?: boolean;
/**
* Base path for the share-link REST surface. Defaults to
* `/api/v1/share-links`.
*/
shareLinkBasePath?: string;
}
/**
* [#2926 ③] Boot backfill: rule grants are materialized by the write hooks,
* and this pass covers the rows those hooks did not reach.
*
* [#13533] It was originally written for seed rows, which are written with
* `isSystem` and which the hooks used to skip — so a fresh deploy's seed data
* carried no `sys_record_share` rows until each record was touched at runtime.
* That skip is gone (see the retirement note in `rule-hooks.ts`), and this pass
* is still owed: rows written while a rule was inactive or before its hooks
* were bound are unreached by any hook, and this is the only pass that PURGES
* a deactivated rule's grants (#4433).
*
* Reconcile every rule once per boot: `evaluateRule` is idempotent
* (diff-based grant/update/revoke), so repeated boots are no-ops.
* Best-effort per rule — one broken rule must not block startup or its
* siblings. Returns the number of rules successfully reconciled.
*
* [#4433] Callers must pass EVERY rule, not just the active ones. This pass is
* the last line of defence for withdrawal: `evaluateRule` purges the grants of
* a rule it finds inactive, so an inactive rule in this list is what turns a
* restart into a repair. Handed only active rules — as it was — the pass could
* physically never revoke anything a deactivated rule had left behind, which
* is why the #4433 repro survived a full restart with the rule reading
* `active: false` and the grant still answering.
*/
export async function backfillRuleGrants(
ruleService: SharingRuleService,
rules: Array<{ id?: string; name?: string }>,
logger?: { info?: (msg: string, meta?: any) => void; warn?: (msg: string, meta?: any) => void },
): Promise<number> {
const start = Date.now();
let reconciled = 0;
// [ADR-0131 D2] A declared rule under a wall is listed once per organization,
// every projection under its one id, and `evaluateRule(id)` already passes
// over all of them — so each id is evaluated once.
const evaluated = new Set<string>();
for (const rule of rules) {
const key = (rule.id ?? rule.name) as string;
if (evaluated.has(key)) continue;
evaluated.add(key);
try {
await ruleService.evaluateRule(key, { isSystem: true } as any);
reconciled += 1;
} catch (err: any) {
logger?.warn?.('SharingServicePlugin: boot rule backfill failed for rule', {
rule: rule.name ?? rule.id,
error: err?.message,
});
}
}
if (rules.length > 0) {
logger?.info?.('SharingServicePlugin: boot rule backfill done', {
rules: rules.length,
reconciled,
ms: Date.now() - start,
});
}
// [#3929 follow-up] One aggregate line for the legacy criteria-less rules
// the pass just walked (each also warned once, above, via the per-rule
// dedup): the operator-facing summary of what is under-sharing and why.
const inert = ruleService.inertRuleNames;
if (inert.length > 0) {
logger?.warn?.(
'SharingServicePlugin: rule(s) with no usable criteria are matching NO records — their ' +
'grants are revoked on reconcile (ADR-0049). Fix the criteria or set active: false.',
{ count: inert.length, rules: inert },
);
}
return reconciled;
}
/**
* [#3865] Boot backfill: normalise stored `access_level: 'full'` rows to
* `'edit'` on `sys_sharing_rule` and `sys_record_share`.
*
* `full` was declared "Full Access (Transfer, Share, Delete)" but no code path
* granted any of those verbs because of it — both enforcement gates matched
* `access_level in ('edit','full')`, so it was byte-equivalent to `edit`
* (ADR-0078 declared-but-unenforced). Having retired it from the authoring
* surface, this closes the loop on rows already persisted.
*
* **Behaviour-preserving by construction**: the two levels were already
* equivalent, so no principal gains or loses access. Contrast the OWD
* `sharingModel: 'full'` retirement (ADR-0090 D4), which changed posture and
* therefore had to be delegated to the author rather than auto-migrated.
*
* Writes with `isSystem` so the provenance stamp hook treats this as the
* package door, not an admin edit — a package-seeded rule must NOT come out of
* this marked `customized`, or the seeder would stop updating it forever
* (#2909 T1).
*
* Best-effort and idempotent: a missing table or a failed row is logged and
* skipped, never fatal to boot, and a second run finds nothing to do.
*/
export async function backfillRetiredAccessLevels(
engine: SharingEngine,
logger?: { info?: (msg: string, meta?: any) => void; warn?: (msg: string, meta?: any) => void },
): Promise<{ rules: number; shares: number }> {
const BATCH = 500;
const SYS = { isSystem: true, positions: [], permissions: [] } as any;
const counts = { rules: 0, shares: 0 };
const normalizeObject = async (object: 'sys_sharing_rule' | 'sys_record_share'): Promise<number> => {
let migrated = 0;
// Re-query per batch rather than paginating: each pass mutates the very
// predicate it selects on, so offsets would skip rows. Bounded by a
// no-progress break so a silently-failing update can't spin forever.
for (;;) {
const rows = await engine.find(object, {
where: { access_level: 'full' },
fields: ['id'],
limit: BATCH,
context: SYS,
});
const batch = Array.isArray(rows) ? rows : [];
if (batch.length === 0) break;
let updatedThisPass = 0;
for (const row of batch) {
const id = (row as any)?.id;
if (!id) continue;
try {
await engine.update(object, { id, access_level: 'edit' }, { context: SYS });
updatedThisPass += 1;
} catch (err: any) {
logger?.warn?.('SharingServicePlugin: access-level backfill failed for row', {
object,
id,
error: err?.message,
});
}
}
migrated += updatedThisPass;
if (updatedThisPass === 0) {
logger?.warn?.('SharingServicePlugin: access-level backfill made no progress — stopping', {
object,
remaining: batch.length,
});
break;
}
}
return migrated;
};
for (const object of ['sys_sharing_rule', 'sys_record_share'] as const) {
try {
const migrated = await normalizeObject(object);
if (object === 'sys_sharing_rule') counts.rules = migrated;
else counts.shares = migrated;
} catch (err: any) {
// Table absent (plugin loaded without its objects) or driver refusing the
// filter — never fatal, the gates still honour `full` meanwhile.
logger?.warn?.('SharingServicePlugin: access-level backfill skipped', {
object,
error: err?.message,
});
}
}
if (counts.rules > 0 || counts.shares > 0) {
logger?.info?.("SharingServicePlugin: normalised retired access_level 'full' → 'edit'", counts);
}
return counts;
}
/**
* SharingServicePlugin — registers `sys_record_share`, the `sharing`
* service, and the engine middleware that enforces
* `object.sharingModel`.
*
* Enforcement is opt-in per object:
*
* - `sharingModel: 'private'` → reads filtered to `(owner_id == me) OR
* (record explicitly shared with me)`. Writes require ownership or
* an `edit` share.
* - `sharingModel: 'public_read'` → reads unrestricted; writes gated as
* above (typical "everyone can see, only owner can edit").
* - any other value (or no value) → no enforcement. This keeps
* existing CRM behaviour identical until admins explicitly enable
* sharing on a per-object basis.
*
* @example
* ```ts
* import { SharingServicePlugin } from '@objectstack/plugin-sharing';
*
* kernel.use(new SharingServicePlugin());
*
* // Mark an object private — middleware enforces from this point on.
* defineObject({
* name: 'account',
* sharingModel: 'private',
* fields: { owner_id: Field.lookup('sys_user'), ... },
* });
* ```
*/
export class SharingServicePlugin implements Plugin {
name = 'com.objectstack.service.sharing';
version = '1.0.0';
type = 'standard' as const;
dependencies = ['com.objectstack.engine.objectql'];
private readonly options: SharingPluginOptions;
private service?: SharingService;
private ruleService?: SharingRuleService;
private linkService?: ShareLinkService;
/** Resolved once in `kernel:ready`; reused by the `kernel:bootstrapped` backfills. */
private engine?: SharingEngine;
/**
* [ADR-0142 D1] The ownership-queue service, constructed and registered in
* `init` — before any `kernel:ready` handler runs — so the engine's boot
* refusal for a stack declaring `queues` / `assignmentRules` finds it. It
* reaches the engine lazily, at use.
*/
private queues?: OwnershipQueueService;
/**
* [#4433] Has the `kernel:bootstrapped` rule-grant backfill finished?
*
* This is the real question the rule-write trigger needs to answer before it
* decides to skip a reconcile — "is the boot pass going to cover this write
* anyway?" It used to ask `session.isSystem` instead, which is a different
* question with a very different answer: `SharingRuleService.defineRule`
* writes `sys_sharing_rule` with SYSTEM_CTX **always** (it must, to reach a
* platform table the sharing middleware otherwise gates), so every runtime
* authoring write — including `POST /sharing/rules` with `active: false` —
* looked exactly like boot seeding and was skipped. That is the whole of
* #4433's first half: deactivation returned 200, and nothing reconciled.
*/
private ruleGrantsBootReconciled = false;
constructor(options: SharingPluginOptions = {}) {
this.options = options;
}
/**
* Serializes rule-hook rebinds triggered by `sys_sharing_rule` data
* changes, so two rapid writes can't interleave their unbind→bind
* sequences and leave the older rule snapshot bound.
*/
private ruleRebindChain: Promise<void> = Promise.resolve();
/**
* The plugin's ONE binding site for the per-record sharing-rule hooks, at
* boot and on every `sys_sharing_rule` rebind ({@link bindRuleRebindTriggers})
* — so the two can never derive different object sets. It unbinds the
* rule-hook package and binds it again on `listRuleHookObjects()`
* (`rebindRuleHooks`, rule-hooks.ts): per OBJECT, from the declarations and
* rows, never from the organizations a declared rule is served in at this
* moment. An organization created after boot (the organization-created
* middleware, `addDeclaredRuleScope`) is therefore served by the hooks
* already bound; the organization is resolved when a record is evaluated.
*/
private async bindRuleHooks(engine: any, ctx: PluginContext): Promise<void> {
const ruleService = this.ruleService;
if (!ruleService) return;
await rebindRuleHooks(engine, ruleService, ctx.logger as any);
}
/**
* [#2592] Rebind rule hooks whenever `sys_sharing_rule` DATA changes.
*
* `bindRuleHooks` above runs once at `kernel:ready` and registers
* lifecycle hooks only for the objects that had ≥1 rule at that moment.
* Rule *evaluation* reads `sys_sharing_rule` live, but a rule created at
* runtime for an object with no boot-time rule never got a hook — so it
* silently no-oped until the next restart. And because authoring a rule
* is a data INSERT (not a metadata publish), the `metadata:reloaded`
* rebind pattern (#2576) never fires here — the trigger must be a
* data-change hook on the rule table itself.
*
* The rebind mirrors boot exactly: both go through {@link bindRuleHooks},
* which unbinds the whole rule-hook package and re-binds it from a fresh
* `listRuleHookObjects()`. Runs AFTER the write inside the
* same lifecycle pipeline (awaited, so the rule is enforceable the moment
* the authoring call returns), but never fails the write — a rebind
* failure logs and leaves the previous bindings in place.
*
* [#3821] The rebind alone only makes the rule apply to records written
* FROM NOW ON. Authoring in the Setup UI therefore looked inert: an admin
* created a rule, switched it on, and the recipient still saw nothing —
* the rule only reached a record once somebody happened to touch it. Worse
* in the other direction, switching a rule OFF (or deleting it) left every
* grant it had already issued in place, and boot backfill only reconciles
* ACTIVE rules, so those grants survived restarts forever: the UI said
* "disabled" while the access was still live.
*
* So each write now also reconciles THAT rule's grants — the same
* `evaluateRule` the REST `/sharing/rules/:id/evaluate` endpoint runs, which
* is diff-based and purges when the rule is inactive. Deletes can't go
* through it (the row is gone, `RULE_NOT_FOUND`), so they purge directly.
*
* [#4433] The reconcile is skipped only until the `kernel:bootstrapped`
* backfill has run — NOT for every `isSystem` write, as it was. #3821 built
* this seam and then gated it on the one predicate that switches it off
* everywhere it mattered: `defineRule` — the sole implementation behind
* `POST /sharing/rules`, the documented way to deactivate a rule — writes
* with SYSTEM_CTX unconditionally, so the `isSystem` skip caught 100% of
* REST authoring. The withdrawal path was present, tested (against a mocked
* `session` the real path never sends) and unreachable in production: an
* admin saving `active: false` got a 200 and no reconcile, and because boot
* backfill then only walked ACTIVE rules, the orphaned grant outlived every
* restart. Boot phase is the honest predicate — before it, the backfill owes
* this table a pass; after it, nothing else will do the work.
*/
private bindRuleRebindTriggers(engine: any, ctx: PluginContext): void {
const scheduleRebind = (): Promise<void> => {
const run = this.ruleRebindChain.then(() => this.bindRuleHooks(engine, ctx));
// The chain must never hold a rejection (it would poison later
// rebinds); callers observe failures through `run`.
this.ruleRebindChain = run.catch(() => undefined);
return run;
};
/**
* Reconcile the written rule's grants, chained behind the rebind so two
* rapid writes can't interleave their reconciles. Best-effort: a failure
* logs and leaves the previous grants alone — it must never fail the
* authoring write.
*/
const scheduleReconcile = (ruleId: string, deleted: boolean): Promise<void> => {
const run = this.ruleRebindChain.then(async () => {
const ruleService = this.ruleService;
if (!ruleService) return;
if (deleted) {
await ruleService.revokeRuleGrants(ruleId);
return;
}
await ruleService.evaluateRule(ruleId, { isSystem: true } as any);
});
this.ruleRebindChain = run.catch(() => undefined);
return run;
};
const makeHandler = (deleted: boolean) => async (hookCtx: any) => {
try {
await scheduleRebind();
} catch (err: any) {
ctx.logger.warn('SharingServicePlugin: sharing-rule hook rebind failed — previous bindings kept', {
error: err?.message,
});
}
// [#4433] Skip only while the boot backfill still owes this table a
// pass. Declared-rule seeding and package bootstrap run before
// `kernel:bootstrapped`, and that pass reconciles every rule, so
// reconciling here would duplicate it. Once it has run, every write
// reconciles — regardless of `isSystem`, which cannot distinguish boot
// seeding from an admin's `POST /sharing/rules` (both arrive as
// SYSTEM_CTX from `defineRule`).
if (!this.ruleGrantsBootReconciled) return;
const data = hookCtx?.result ?? hookCtx?.input?.data ?? {};
const ruleId = String(data?.id ?? hookCtx?.input?.id ?? '');
if (!ruleId) return;
try {
await scheduleReconcile(ruleId, deleted);
} catch (err: any) {
ctx.logger.warn('SharingServicePlugin: sharing-rule grant reconcile failed — grants left unchanged', {
rule: ruleId,
error: err?.message,
});
}
};
for (const event of ['afterInsert', 'afterUpdate', 'afterDelete']) {
engine.registerHook(event, makeHandler(event === 'afterDelete'), {
object: 'sys_sharing_rule',
packageId: RULE_REBIND_TRIGGER_PACKAGE,
priority: 200,
});
}
ctx.logger.info('SharingServicePlugin: sharing-rule data-change rebind triggers bound');
}
/**
* [#15349] The share-link ADMISSION seam's EFFECTIVE tenancy posture.
*
* ## What was open
*
* `resolveAuthzContext` gates every posture-conditional refusal on a posture
* its CALLER supplies, and this door supplied none — so none of them ran:
*
* - `organization_required` (`core/security/api-key.ts`, `if (!tenantId &&
* tenancyPosture)`),
* - `organization_membership_ended` (`core/security/resolve-authz-context.ts`,
* `if (keyPrincipal?.tenantId && input.tenancyPosture)`),
* - and the #15409 SESSION arm beside it, which drops an
* `activeOrganizationId` claim no `sys_member` row backs.
*
* An API key's `tenantId` is `sys_api_key.active_organization_id` copied
* verbatim — the caller's own stored claim, never vetted against current
* membership. Under a wall-enforcing posture a key stamped with an
* organization its owner has LEFT was therefore admitted here carrying that
* organization as its tenant, and minted share links — capability tokens —
* on that organization's records.
*
* ## ⛔ Why this plugin's EXISTING `tenancy` probes are the wrong value
*
* Two are already resolved a few hundred lines up, and BOTH swallow failure
* as absence: the `tenancy: () => { try { … } catch { return null; } }` option
* handed to `SharingService`, and `sharingPosture()`, whose own catch falls
* through to the walled default. Reusing either
* accessor here would re-introduce exactly the permissive-on-failure defect
* #13906 exists to repair — a `tenancy` service that was WIRED and BROKE
* reading as "this check does not apply". Those two are also answering a
* different question: their fallback is *walled*, which is fail-closed for a
* seeding/scope decision and would be fail-OPEN nonsense for an admission one
* (`undefined` means "run no posture-conditional refusal at all", while
* `'single'` is a posture that is present and simply enforces no wall).
*
* ## The classification — #13906 decision 1 option A, no longer written here
*
* [#16013] `classifyAdmissionTenancyPosture` (`@objectstack/core`) owns the
* branded/unbranded decision for every admission seam: never registered ⇒
* quiet `undefined`; every other rejection ⇒ `AuthzStoreUnavailableError`
* (ADR-0112 `SERVICE_UNAVAILABLE` / 503), because admission was never DECIDED
* and must not be answered. One tested classification, so it cannot decay
* into a silent `catch` at one seam while five others stay correct.
*
* ⚠️ What that decision MEANS at this door is still this door's own. Quiet
* arm: an embedding with no `plugin-auth` is a SUPPORTED composition and its
* behaviour here is exactly what it was. Loud arm:
* `verifiedContextFromRequest`'s `catch` already re-raises this brand rather
* than laundering it into a 401 (commit 6a180e42d), and the routes' own `catch` answers
* `err.status` — so the outage reaches the wire as a 503.
*
* ⚠️ The brand exists only on the ASYNC resolution path: `PluginContext.getService`
* throws two UNBRANDED plain `Error`s (`… not found` and `… is async - use
* await`), so a synchronous read cannot tell the two facts apart and would
* have to guess. Hence `getServiceAsync`, reached through `getKernel()`.
*
* ⚠️ The ASYNC ACCESSOR's presence is part of the wiring fact, exactly as on
* the two sibling seams (`rest-server.ts`, `marketplace-install-local-plugin.ts`):
* a `KernelBase`-shaped host (`LiteKernel`) exposes `getKernel()` but has no
* `getServiceAsync` at all, so dereferencing it would raise an unbranded —
* therefore LOUD — `TypeError`, turning "this host shape has no async
* registry" into an outage. Such a host has no service factories either
* (`registerServiceFactory` throws "not supported"), so absence is the only
* fault it could report. It keeps the quiet answer, unchanged.
*/
private resolveAdmissionTenancyPosture = async (
ctx: PluginContext,
): Promise<TenancyPosture | undefined> => {
const kernel = ctx.getKernel?.() as
| { getServiceAsync?: <T>(name: string, scopeId?: string) => Promise<T> }
| undefined;
if (!kernel || typeof kernel.getServiceAsync !== 'function') return undefined;
return classifyAdmissionTenancyPosture(() =>
kernel.getServiceAsync!<TenancyPostureSource>('tenancy'),
);
};
/**
* [#30209 row 5 B] Mount `GET /api/v1/sharing/shareable-objects`
* (`shareable-objects-routes.ts`, ledger `sharing-route-ledger.ts`). The
* list is `SharingRuleService.listShareableObjects`, read at request time,
* so a rule service that never started answers 501 there instead of the
* path going unmounted. Canonical `http.server` first, the deprecated
* `http-server` alias second, as the share-link mount reads them.
*/
private mountShareableObjectsRoute(ctx: PluginContext): void {
const readServer = (name: string): IHttpServer | null => {
try { return ctx.getService<IHttpServer>(name); } catch { return null; }
};
const http: IHttpServer | null = readServer('http.server') ?? readServer('http-server');
if (!http) {
ctx.logger.warn(
'SharingServicePlugin: no HTTP server — GET ' + SHAREABLE_OBJECTS_ROUTE + ' (the sharing-rule object '
+ 'picker list) not registered. SharingRuleService.listShareableObjects is still reachable via '
+ 'kernel.getService("sharingRules").',
);
return;
}
const optional = <T>(name: string): T | undefined => {
try { return ctx.getService<T>(name); } catch { return undefined; }
};
const kernel = ctx.getKernel?.() as
| { getServiceAsync?: <T>(name: string) => Promise<T> }
| undefined;
registerShareableObjectsRoutes(http, {
getEngine: () => optional<unknown>('objectql'),
getAuth: () => optional<RequestAuthService>('auth'),
tenancy: kernel && typeof kernel.getServiceAsync === 'function'
? () => kernel.getServiceAsync!<TenancyPostureSource>('tenancy')
: undefined,
listShareableObjects: (context) => {
if (!this.ruleService) throw new SharingRulesNotRunningError();
return this.ruleService.listShareableObjects(context);
},
});
ctx.logger.info(`SharingServicePlugin: shareable objects list mounted at GET ${SHAREABLE_OBJECTS_ROUTE}`);
}
async init(ctx: PluginContext): Promise<void> {
// Register sys_record_share via the manifest service.
ctx.getService<{ register(m: any): void }>('manifest').register({
id: 'com.objectstack.service.sharing',
name: 'Sharing Service',
version: '1.0.0',
type: 'plugin',
scope: 'system',
defaultDatasource: 'cloud',
namespace: 'sys',
objects: [
SysRecordShare,
SysSharingRule,
SysBusinessUnit,
SysBusinessUnitMember,
SysShareLink,
// [ADR-0142 D1/D5] Authored queues, their members, the round-robin
// cursor the engine's assignment step advances, and an organization's
// own assignment rules (ruling A on organization-authored routing).
SysQueue,
SysQueueMember,
SysAssignmentCursor,
SysAssignmentRule,
],
// The queue's record page: its fields, and its members listed by the
// queue's name with "New" pre-filled (`sys-queue.page.ts`).
pages: [SysQueueDetailPage],
// ADR-0029 D7 — contribute the sharing and routing entries into the
// Setup app. This plugin owns these objects (K2).
//
// [#39058, epic #39050 rows 2 and 4] Two slots, each named directly: the
// retired `group_access_control` id would put all five entries in Access
// & Sharing through `renamedFrom`, with a warning, and the epic's table
// splits them.
// - Access & Sharing (`group_access_sharing`, 200): Sharing Rules and
// Record Shares, after plugin-security's Position Members and
// Permission Set Grants (150).
// - Routing & Approvals (`group_routing_approvals`, 200): Assignment
// Rules, then the work queues, after plugin-approvals' entries
// (100). That group carries `manage_platform_settings`, which each
// of these entries already declares, so who sees them does not
// change.
//
// [ADR-0131 D6, regime C] A sharing rule has two sources: `nav_sharing_rules`
// opens the organization's own rules (`sys_sharing_rule` rows). The rules
// packages declare are registry items with no object behind them, and
// [ADR-0146 D1] Setup carries no metadata catalog: they are listed and
// switched on and off in Studio's "All metadata" area, so no entry here
// opens them.
navigationContributions: [
{
app: 'setup',
group: 'group_access_sharing',
priority: 200,
items: [
{ id: 'nav_sharing_rules', type: 'object', label: 'Sharing Rules', objectName: 'sys_sharing_rule', icon: 'share-2', requiresObject: 'sys_sharing_rule', requiredPermissions: ['manage_platform_settings'] },
{ id: 'nav_record_shares', type: 'object', label: 'Record Shares', objectName: 'sys_record_share', viewName: 'all_shares', icon: 'link', requiresObject: 'sys_record_share', requiredPermissions: ['manage_platform_settings'] },
],
},
{
app: 'setup',
group: 'group_routing_approvals',
priority: 200,
items: [
{ id: 'nav_assignment_rules', type: 'object', label: 'Assignment Rules', objectName: 'sys_assignment_rule', icon: 'route', requiresObject: 'sys_assignment_rule', requiredPermissions: ['manage_platform_settings'] },
{ id: 'nav_queues', type: 'object', label: 'Queues', objectName: 'sys_queue', icon: 'inbox', requiresObject: 'sys_queue', requiredPermissions: ['manage_platform_settings'] },
{ id: 'nav_queue_members', type: 'object', label: 'Queue Members', objectName: 'sys_queue_member', icon: 'users', requiresObject: 'sys_queue_member', requiredPermissions: ['manage_platform_settings'] },
],
},
],
});
// 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<II18nService>('i18n');
if (i18n && typeof i18n.loadTranslations === 'function') {
const { SharingTranslations } = await import('./translations/index.js');
for (const [locale, data] of Object.entries(SharingTranslations)) {
i18n.loadTranslations(locale, data as Record<string, unknown>);
}
}
} catch { /* i18n optional */ }
});
}
// [ADR-0142 D1] The ownership-queue service — registered here, in `init`,
// under its own name (⛔ never `queue`, the job queue's): the engine's
// `kernel:ready` boot refusal tests for it by that name, and a `kernel:ready`
// registration could lose the race to it. The engine is resolved at use.
this.queues = new OwnershipQueueService({
engine: () => {
if (this.engine) return this.engine as OwnershipQueueEngine;
try { return ctx.getService<OwnershipQueueEngine>('objectql'); } catch { return null; }
},
logger: ctx.logger as any,
});
ctx.registerService(OWNERSHIP_QUEUE_SERVICE, this.queues);
ctx.logger.info('SharingServicePlugin: schema registered');
}
async start(ctx: PluginContext): Promise<void> {
ctx.hook('kernel:ready', async () => {
// The engine SEEN WHOLE (`registerHook` / `unregisterHooksByPackage` /
// `registerMiddleware` are all bound below), which is the `objectql`
// slot. Its ledger entry records it as "the SAME instance as `data`,
// seen whole", so the alias fallback resolves the same object.
let engine: IObjectQLEngine | null = null;
try { engine = ctx.getService<IObjectQLEngine>('objectql'); }
catch { try { engine = ctx.getService<IObjectQLEngine>('data'); } catch { /* ignore */ } }
if (!engine) {
ctx.logger.warn('SharingServicePlugin: no ObjectQL engine — service NOT registered');
return;
}
this.engine = engine as SharingEngine;
this.service = new SharingService({
engine: engine as SharingEngine,
bypassObjects: this.options.bypassObjects,
logger: ctx.logger as any,
// [ADR-0057] Late-bound lookup of the enterprise hierarchy resolver.
// Open edition: not registered → hierarchy scopes fail closed to own.
hierarchyResolver: () => {
try { return ctx.getService<IHierarchyScopeResolver>('hierarchy-scope-resolver'); }
catch { return null; }
},
// [ADR-0111 D1/D2] Late-bound security probe for canManageShares'
// Modify-All path. Absent (no plugin-security) → owner-only, fail
// closed — a degraded security stack never widens sharing authority.
securityService: () => {
// The named surface this option already requires — plugin-security is
// OPTIONAL, so the consumer declares the slice it probes rather than
// taking a runtime dependency on `ISecurityService`.
try { return ctx.getService<SharingSecurityProbe>('security'); }
catch { return null; }
},
// [ADR-0105 D1 / #5859] Late-bound tenancy posture — read exactly the
// way SecurityPlugin reads it for the Layer 0 wall, so the two layers
// can never disagree about whether an organization wall is in force.
// Absent (no plugin-auth) → the org gate assumes WALLED and refuses to
// widen a hierarchy scope that carries no organization; an unresolvable
// posture is not evidence of `single`.
tenancy: () => {
try { return ctx.getService<SharingTenancyProbe>('tenancy'); }
catch { return null; }
},
// [ADR-0142 D3] Records sitting in the caller's queues.
ownershipQueues: () => this.queues ?? null,
// [#26180] Late-bound `approvals` service: the records a pending
// approver may read, ORed into the read filter. Optional plugin, so
// the slice is declared structurally; absent → no approval grant.
approvals: () => {
try { return ctx.getService<SharingApprovalReadProbe>('approvals'); }
catch { return null; }
},
});
ctx.registerService('sharing', this.service);
// [ADR-0142 D1] The authored queue tables' name guards — data hygiene on
// tables this plugin owns, bound regardless of `enforce` — and the boot
// report of an authored queue a later declaration shadows.
try {
if (this.queues && typeof engine.registerHook === 'function') {
bindQueueGuards(engine as any, this.queues);
await reportShadowedAuthoredQueues(engine as any, this.queues, ctx.logger as any);
}
} catch (err: any) {
ctx.logger.warn('SharingServicePlugin: queue guards not bound', { error: err?.message });
}
// [ADR-0142 D5, ruling A on organization-authored routing] An
// organization's own assignment rules: the save guard on the table this
// plugin owns (name namespace, object, entry shape, CEL compile, user
// target membership), bound regardless of `enforce`, and the boot report
// of an authored rule a later declaration shadows.
try {
if (typeof engine.registerHook === 'function') {
bindAssignmentRuleGuards(engine as any);
await reportShadowedAuthoredAssignmentRules(engine as any, ctx.logger as any);
}
} catch (err: any) {
ctx.logger.warn('SharingServicePlugin: assignment-rule guard not bound', { error: err?.message });
}
// [ADR-0057 D12] Maintain sys_user.primary_business_unit_id as a
// denormalised projection of sys_business_unit_member.is_primary so a
// user-lookup can filter candidates by business unit. Bound regardless of
// `enforce` — it is a data projection, not an access-control surface.
try {
if (typeof engine.registerHook === 'function' && typeof engine.unregisterHooksByPackage === 'function') {
bindPrimaryBuHooks(engine, ctx.logger as any);
await backfillPrimaryBu(engine, ctx.logger as any);
}
} catch (err: any) {
ctx.logger.warn('SharingServicePlugin: primary-bu projection not started', { error: err?.message });
}
// [#5103] Record delete ⇒ every share on that record is revoked, whatever
// its source. Bound REGARDLESS of `enforce`, and deliberately: with
// enforcement off the rows are not consulted, but they are still written
// (by rules, by the share REST surface in a host that mounts it) and
// still accumulate — and a deployment that flips `enforce` back on must
// not inherit a table of dangling grants. Same reasoning as the primary-BU
// projection above: this is data hygiene on a table this plugin owns, not
// an access-control surface.
//
// Not bound per object: the posture is judged per delete from live
// metadata, so an object that gains `sharingModel` after boot is covered
// without a rebind (see record-share-cascade.ts).
//
// [#5190] The same hook pair also reclaims `sys_share_link` — a link is a
// capability token, so an orphan of it is worse than an orphaned grant:
// no principal is named, and a reused record id hands the new record to
// whoever kept the URL. The link service is passed as a GETTER because it
// is constructed further down this same handler; `resolveToken` refuses
// dead-record links regardless of whether this hook ever runs.
try {
if (typeof engine.registerHook === 'function' && typeof engine.unregisterHooksByPackage === 'function') {
bindRecordShareCascade(engine, this.service, ctx.logger as any, () => this.linkService);
} else {
ctx.logger.warn(
'SharingServicePlugin: engine has no hook API — record deletes will NOT revoke their ' +
'sys_record_share / sys_share_link rows; the kernel:bootstrapped orphan sweeps are the ' +
'only reclaim',
);
}
} catch (err: any) {
ctx.logger.warn('SharingServicePlugin: record-share delete cascade not bound', { error: err?.message });
}
// Enforcement (read-filter middleware + sharing-rule hooks) is opt-out
// via `enforce: false`. The share-link service below is registered
// REGARDLESS — capability-token sharing does not depend on principal-
// based RLS enforcement, and multi-tenant hosts mount this plugin purely
// for the `shareLinks` service (per-env enforcement is applied elsewhere).
if (this.options.enforce === false) {
ctx.logger.info('SharingServicePlugin: enforcement disabled (enforce=false) — share-link service still registered');
} else {
const mw = buildSharingMiddleware(this.service, ctx.logger as any, pluginMessageTranslator(ctx));
if (typeof engine.registerMiddleware === 'function') {
engine.registerMiddleware(mw, { object: '*' });
// [#27175] The by-id write gate now meets every by-id write, so a
// reader asking `admitsByIdWrite` is asking a gate that is enforced.
this.service.byIdWriteGateInstalled = true;
ctx.logger.info('SharingServicePlugin: enforcement middleware installed');
} else {
ctx.logger.warn('SharingServicePlugin: engine has no registerMiddleware — enforcement not applied');
}
// Rule evaluator + hot-rebindable lifecycle hooks.
try {
// [ADR-0131 D2] Declared `sharingRules` are READ from the registry
// on every read of the rule set, never copied into `sys_sharing_rule`
// — the seeder that copied them (`bootstrapDeclaredSharingRules`) is
// retired. The metadata service is resolved at read time: it is the
// registry-less host's reader and may register after this plugin.
this.ruleService = new SharingRuleService({
engine: engine as SharingEngine,
sharing: this.service,
logger: ctx.logger as any,
// [ADR-0142 D7] A `queue` recipient expands through the queue service.
ownershipQueues: () => this.queues ?? null,
declaredRules: createDeclaredSharingRuleSource({
engine,
metadata: () => {
try { return ctx.getService<IMetadataService>('metadata'); } catch { return null; }
},
logger: ctx.logger as any,
}),
});
ctx.registerService('sharingRules', this.ruleService);
// [#10103] Declared rules are served ONCE PER ORGANIZATION under a
// walled posture and organization-less under `single` — the passes
// the retired seeder made. A rule served organization-less on a
// walled deployment would sweep every tenant's records; under
// `single` the organization-less rule is the platform-global class
// `deleteRule` guards (#7795).
// The posture, read EXACTLY the way this plugin already reads it for
// the hierarchy org gate (the `tenancy` service, ADR-0105 D1 / #5859),
// so the two layers can never disagree about whether a wall is in
// force. An unresolvable posture is NOT evidence of `single`: it is
// treated as walled, because serving organization-less on a walled
// deployment is the failure #10103 removed, while an unnecessary
// per-organization scope on a `single` deployment costs one read.
const sharingPosture = (): TenancyPosture => {
try {
const probe = ctx.getService<SharingTenancyProbe>('tenancy');
const normalized = normalizeTenancyPosture(probe?.posture);
if (normalized) return normalized;
if (probe?.isolationActive === false) return 'single';
} catch { /* absent — fall through to the walled default */ }
return 'isolated';
};