-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsharing-plugin.ts
More file actions
545 lines (516 loc) · 23.9 KB
/
Copy pathsharing-plugin.ts
File metadata and controls
545 lines (516 loc) · 23.9 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import type { Plugin, PluginContext } from '@objectstack/core';
import { resolveAuthzContext } from '@objectstack/core';
import type { EngineMiddleware, OperationContext } from '@objectstack/objectql';
import type { IHttpServer, IHttpRequest, ShareLinkExecutionContext } from '@objectstack/spec/contracts';
import { SysRecordShare, SysSharingRule, SysShareLink } from './objects/index.js';
import { SysBusinessUnit, SysBusinessUnitMember } from '@objectstack/platform-objects/identity';
import { SharingService, type SharingEngine } from './sharing-service.js';
import { SharingRuleService } from './sharing-rule-service.js';
import { ShareLinkService } from './share-link-service.js';
import { registerShareLinkRoutes } from './share-link-routes.js';
import { bindRuleHooks, unbindAllRuleHooks, 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 { bootstrapDeclaredSharingRules } from './bootstrap-declared-sharing-rules.js';
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,
* but seed rows are written with `isSystem` (which the hooks deliberately
* skip — see rule-hooks.ts), so a fresh deploy's seed data carried no
* `sys_record_share` rows until each record was touched at runtime.
* Reconcile every active 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.
*/
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;
for (const rule of rules) {
try {
await ruleService.evaluateRule((rule.id ?? rule.name) as string, { 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,
});
}
return reconciled;
}
/**
* 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`/`full` 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';
dependencies = ['com.objectstack.engine.objectql'];
private readonly options: SharingPluginOptions;
private service?: SharingService;
private ruleService?: SharingRuleService;
private linkService?: ShareLinkService;
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();
/**
* [#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: unbind the whole rule-hook package,
* re-bind from a fresh `listRules()`. 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.
*/
private bindRuleRebindTriggers(engine: any, ctx: PluginContext): void {
const scheduleRebind = (): Promise<void> => {
const run = this.ruleRebindChain.then(async () => {
const ruleService = this.ruleService;
if (!ruleService) return;
const rules = await ruleService.listRules({ activeOnly: true }, { isSystem: true } as any);
unbindAllRuleHooks(engine);
bindRuleHooks(engine, ruleService, rules, ctx.logger as any);
});
// The chain must never hold a rejection (it would poison later
// rebinds); callers observe failures through `run`.
this.ruleRebindChain = run.catch(() => undefined);
return run;
};
const handler = async () => {
try {
await scheduleRebind();
} catch (err: any) {
ctx.logger.warn('SharingServicePlugin: sharing-rule hook rebind failed — previous bindings kept', {
error: err?.message,
});
}
};
for (const event of ['afterInsert', 'afterUpdate', 'afterDelete']) {
engine.registerHook(event, handler, {
object: 'sys_sharing_rule',
packageId: RULE_REBIND_TRIGGER_PACKAGE,
priority: 200,
});
}
ctx.logger.info('SharingServicePlugin: sharing-rule data-change rebind triggers bound');
}
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-0029 D7 — contribute the sharing entries into the Setup app's
// `group_access_control` slot (priority 200 so they sit after plugin-
// security's Roles / Permission Sets). This plugin owns these objects (K2).
navigationContributions: [
{
app: 'setup',
group: 'group_access_control',
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', icon: 'link', requiresObject: 'sys_record_share', 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<any>('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 */ }
});
}
ctx.logger.info('SharingServicePlugin: schema registered');
}
async start(ctx: PluginContext): Promise<void> {
ctx.hook('kernel:ready', async () => {
let engine: any = null;
try { engine = ctx.getService<any>('objectql'); }
catch { try { engine = ctx.getService<any>('data'); } catch { /* ignore */ } }
if (!engine) {
ctx.logger.warn('SharingServicePlugin: no ObjectQL engine — service NOT registered');
return;
}
this.service = new SharingService({
engine: engine as SharingEngine,
bypassObjects: this.options.bypassObjects,
// [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<any>('hierarchy-scope-resolver'); }
catch { return null; }
},
});
ctx.registerService('sharing', this.service);
// [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 });
}
// 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);
if (typeof engine.registerMiddleware === 'function') {
engine.registerMiddleware(mw, { object: '*' });
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 {
this.ruleService = new SharingRuleService({
engine: engine as SharingEngine,
sharing: this.service,
logger: ctx.logger as any,
});
ctx.registerService('sharingRules', this.ruleService);
// [ADR-0057 D6 / #2077] Seed stack-declared sharingRules into
// sys_sharing_rule BEFORE listRules so the lifecycle hooks bind to a
// populated table (previously rules were decorative — ruleCount: 0).
try {
let metadataService: any = null;
try { metadataService = ctx.getService<any>('metadata'); } catch { /* optional */ }
if (metadataService) {
await bootstrapDeclaredSharingRules(this.ruleService, metadataService, engine, ctx.logger as any);
}
} catch (err: any) {
ctx.logger.warn('SharingServicePlugin: sharing-rule seeding failed', { error: err?.message });
}
if (typeof engine.registerHook === 'function' && typeof engine.unregisterHooksByPackage === 'function') {
const rules = await this.ruleService.listRules({ activeOnly: true }, { isSystem: true } as any);
unbindAllRuleHooks(engine);
bindRuleHooks(engine, this.ruleService, rules, ctx.logger as any);
this.bindRuleRebindTriggers(engine, ctx);
// [#2909 T1] Stamp `customized` on admin edits of seeded rules so
// the boot seeder stops overwriting them (seed-not-clobber).
unbindRuleProvenanceStamp(engine);
bindRuleProvenanceStamp(engine, ctx.logger as any);
// [#2926 ③] Reconciling existing rows against every rule is
// deferred to `kernel:bootstrapped` (below): seed data is loaded on
// `kernel:ready` (raced against a budget, and the AppPlugin's seed
// hook is a *different* kernel:ready handler), so a backfill here
// would race the very records it must materialize. `kernel:bootstrapped`
// fires only after every kernel:ready handler has settled.
} else {
ctx.logger.warn('SharingServicePlugin: engine has no hook API — sharing rule auto-evaluation disabled');
}
} catch (err: any) {
ctx.logger.warn('SharingServicePlugin: sharing-rule subsystem not started', { error: err?.message });
}
}
// ── Share-Link service (capability tokens) ────────────────
//
// Registered alongside the principal-based sharing service so
// both surfaces resolve through the same kernel. The HTTP
// endpoints are optional — services that just want programmatic
// access can set `registerShareLinkRoutes: false` and call the
// service via `ctx.getService('shareLinks')`.
try {
this.linkService = new ShareLinkService({ engine: engine as SharingEngine });
ctx.registerService('shareLinks', this.linkService);
if (this.options.registerShareLinkRoutes !== false) {
let http: IHttpServer | null = null;
try {
http = ctx.getService<IHttpServer>('http-server');
} catch {
// No HTTP server — service still reachable via getService.
}
if (http) {
// [Finding-2] Derive the caller from the platform's VERIFIED
// resolution (session / API key / OAuth), never from spoofable
// `x-user-id` headers. `positions`/`permissions` flow through so the
// createLink record-access check evaluates real RLS. An
// unresolvable request → anonymous (the authed routes then 401).
const ql: any = engine;
const verifiedContextFromRequest = async (req: IHttpRequest): Promise<ShareLinkExecutionContext> => {
try {
const headers = new Headers();
for (const [k, v] of Object.entries(req.headers ?? {})) {
if (v == null) continue;
headers.set(String(k), Array.isArray(v) ? v.join(',') : String(v));
}
const getSession = async (h: any) => {
try {
const authService: any = ctx.getService('auth');
let api: any = authService?.api;
if (!api && typeof authService?.getApi === 'function') api = await authService.getApi();
return await api?.getSession?.({ headers: h });
} catch {
return undefined;
}
};
const authz = await resolveAuthzContext({ ql, headers, getSession });
return {
userId: authz.userId,
tenantId: authz.tenantId,
positions: authz.positions,
permissions: authz.permissions,
};
} catch {
return {}; // anonymous → authed routes 401
}
};
registerShareLinkRoutes(http, this.linkService, engine as SharingEngine, {
basePath: this.options.shareLinkBasePath,
contextFromRequest: verifiedContextFromRequest,
});
ctx.logger.info(
'SharingServicePlugin: share-link routes mounted at ' +
(this.options.shareLinkBasePath ?? '/api/v1/share-links'),
);
} else {
ctx.logger.warn(
'SharingServicePlugin: no HTTP server — share-link REST routes not registered. ' +
'ShareLinkService is still reachable via kernel.getService("shareLinks").',
);
}
}
} catch (err: any) {
ctx.logger.warn('SharingServicePlugin: share-link subsystem not started', { error: err?.message });
}
});
// [#2926 ③] Materialize sharing grants for rows already present at boot —
// notably SeedLoader-inserted seed records, whose write goes through the
// isSystem short-circuit in the rule hooks and therefore never produces a
// `sys_record_share`. Runs on `kernel:bootstrapped` — the anchor that fires
// after every `kernel:ready` handler (including the AppPlugin seed loader)
// has settled — so the reconcile sees the seeded rows. Idempotent: a runtime
// write that already materialized a grant is reconciled to the same state.
ctx.hook('kernel:bootstrapped', async () => {
if (!this.ruleService) return;
try {
const rules = await this.ruleService.listRules({ activeOnly: true }, { isSystem: true } as any);
await backfillRuleGrants(this.ruleService, rules, ctx.logger as any);
} catch (err: any) {
ctx.logger.warn('SharingServicePlugin: boot rule backfill (kernel:bootstrapped) failed', { error: err?.message });
}
});
}
}
/**
* Build the engine middleware that injects read filters and gates
* write operations. Exported so it can be unit-tested without booting
* a kernel.
*/
export function buildSharingMiddleware(service: SharingService): EngineMiddleware {
return async function sharingMiddleware(ctx: OperationContext, next: () => Promise<void>) {
const op = ctx.operation;
const exec = ctx.context as any;
// READS — AND the visibility filter into the AST.
if (op === 'find' || op === 'findOne' || op === 'count' || op === 'aggregate') {
let filter = await service.buildReadFilter(ctx.object, exec ?? {});
// [ADR-0090 D10] Agent/service intersection on the OWD/sharing axis. When
// the principal acts on behalf of a user, the owner-match and record
// shares are IDENTITY-scoped — so we re-run the visibility filter under
// the DELEGATOR's own identity + depth (stashed by plugin-security as
// `__delegatorReadScope`) and AND it in. The delegated principal then
// sees only rows BOTH identities may see (an over-privileged agent can
// never exceed the user it stands in for). Non-delegated path unchanged.
if (exec?.onBehalfOf?.userId) {
const delFilter = await service.buildReadFilter(ctx.object, {
...exec,
userId: exec.onBehalfOf.userId,
onBehalfOf: undefined,
__readScope: exec.__delegatorReadScope,
});
filter = composeAnd(filter, delFilter);
}
if (filter) {
const ast: any = ctx.ast ?? {};
ast.where = composeAnd(ast.where, filter);
ast.filter = composeAnd(ast.filter, filter);
ctx.ast = ast;
}
return next();
}
// WRITES — gate on canEdit for update / delete.
if (op === 'update' || op === 'delete') {
const data: any = ctx.data;
const options: any = ctx.options;
const id = inferTargetId(data, options);
if (id != null) {
let ok = await service.canEdit(ctx.object, String(id), exec ?? {});
// [ADR-0090 D10] The delegator must ALSO be able to edit the row — an
// on-behalf-of write may only touch rows the delegator could touch.
if (ok && exec?.onBehalfOf?.userId) {
ok = await service.canEdit(ctx.object, String(id), {
...exec,
userId: exec.onBehalfOf.userId,
onBehalfOf: undefined,
__writeScope: exec.__delegatorWriteScope,
});
}
if (!ok) {
const err: any = new Error(
`FORBIDDEN: insufficient privileges to ${op} ${ctx.object} ${id}`,
);
err.code = 'FORBIDDEN';
err.status = 403;
throw err;
}
return next();
}
// Bulk (multi) write — no single id to canEdit-gate (#2982). AND the
// editable-rows filter into the AST so the update/delete only touches
// rows the caller may edit, exactly as the read path scopes finds. The
// engine honours ast.where operation-agnostically (same seam the RLS
// write filter uses). Without this, a `multi:true` write on an
// owner-scoped object would hit every matching row, including peers'.
let writeFilter = await service.buildWriteFilter(ctx.object, exec ?? {});
// [ADR-0090 D10] Intersect the delegator's editable set for on-behalf-of.
if (exec?.onBehalfOf?.userId) {
const delFilter = await service.buildWriteFilter(ctx.object, {
...exec,
userId: exec.onBehalfOf.userId,
onBehalfOf: undefined,
__writeScope: exec.__delegatorWriteScope,
});
writeFilter = composeAnd(writeFilter, delFilter);
}
if (writeFilter) {
const ast: any = ctx.ast ?? {};
ast.where = composeAnd(ast.where, writeFilter);
ast.filter = composeAnd(ast.filter, writeFilter);
ctx.ast = ast;
}
return next();
}
// INSERT / others pass through — ownership stamping is the
// application's job (and is enforced by existing field defaults).
return next();
};
}
function composeAnd(existing: unknown, addition: unknown): unknown {
if (existing == null) return addition;
if (addition == null) return existing;
// Both objects — merge with $and.
if (
typeof existing === 'object' && existing !== null && !Array.isArray(existing) &&
typeof addition === 'object' && addition !== null && !Array.isArray(addition)
) {
const ex: any = existing;
if (Array.isArray(ex.$and)) {
return { $and: [...ex.$and, addition] };
}
// Heuristic: if existing has no operator keys, attempt shallow merge;
// otherwise nest into $and to preserve semantics.
return { $and: [existing, addition] };
}
return { $and: [existing, addition] };
}
function inferTargetId(data: any, options: any): string | number | undefined {
if (data && typeof data === 'object' && data.id != null) return data.id;
if (options && typeof options === 'object') {
if (options.id != null) return options.id;
if (options.where && typeof options.where === 'object' && options.where.id != null) {
return options.where.id;
}
if (options.filter && typeof options.filter === 'object' && options.filter.id != null) {
return options.filter.id;
}
}
return undefined;
}