From 6b71a89a1d9a17f36a6e3e4f035f4e06f32ba272 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 06:23:18 +0000 Subject: [PATCH 1/8] fix(plugin-sharing)!: the sharing scopes carry the share-grant leaf, so every grant counts buildReadFilter and buildWriteFilter write the share arm as the SharedRecordIds leaf (the read form, and the write form on the update scope) in place of the id list they read from sys_record_share under limit 5000. The approval ids stand as a disjunct of their own, delete keeps the owner match alone, and the AST filter mirror no longer carries the scope. On an object whose storage cannot evaluate the leaf (another datasource than sys_record_share, or a driver that does not declare it), share grants stop counting: no scope carries the arm, the edit gate reads no grant, the grant and rule-save doors refuse SHARING_NOT_ENABLED, the explainer says why, and the boot names every such object holding share rows. A host that registers a middleware or a find hook for sys_record_share by name has its boot refused (INTERNAL_ERROR / 500). ADR-0155 plan step 6, with the D6 pins on SQLite and PostgreSQL. Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz Co-authored-by: Claude --- .changeset/33787-shared-record-ids-switch.md | 31 ++ .../controlled-by-parent-leaf-switch.test.ts | 5 +- .../src/controlled-by-parent-sharing.test.ts | 34 +- .../src/explain-dependency-fault.test.ts | 11 +- .../plugin-security/src/explain-engine.ts | 47 ++- .../src/explain-fixed-read-leaf.test.ts | 42 ++- .../src/explain-read-verdict-inputs.test.ts | 5 +- .../src/readable-ids-in-memory.testkit.ts | 14 +- .../src/readable-ids-nested-compose.test.ts | 10 +- .../src/security-plugin-explain-access.ts | 5 + .../shared-record-ids-in-memory.testkit.ts | 77 +++++ .../src/authored-row-write-deferral.test.ts | 13 +- .../src/external-owd-floor.test.ts | 19 +- .../federated-phantom-owner-scoping.test.ts | 21 +- .../src/field-recipient.test.ts | 23 +- .../src/objects/sys-record-share.object.ts | 10 +- .../plugin-sharing/src/share-arm-boot.test.ts | 291 ++++++++++++++++ .../plugin-sharing/src/share-arm-boot.ts | 145 ++++++++ .../src/shared-record-ids-switch.test.ts | 315 ++++++++++++++++++ .../src/shared-record-ids.testkit.ts | 50 +++ .../plugin-sharing/src/sharing-plugin.ts | 40 ++- .../src/sharing-service.test.ts | 147 ++++---- .../plugin-sharing/src/sharing-service.ts | 238 +++++++++---- .../src/system-caller-inert-grant.test.ts | 13 +- .../src/system-write-materialisation.test.ts | 17 +- ...lugin-sharing__src__share-arm-boot.ts.json | 8 + ...ugin-sharing__src__sharing-service.ts.json | 8 + 27 files changed, 1425 insertions(+), 214 deletions(-) create mode 100644 .changeset/33787-shared-record-ids-switch.md create mode 100644 packages/plugins/plugin-security/src/shared-record-ids-in-memory.testkit.ts create mode 100644 packages/plugins/plugin-sharing/src/share-arm-boot.test.ts create mode 100644 packages/plugins/plugin-sharing/src/share-arm-boot.ts create mode 100644 packages/plugins/plugin-sharing/src/shared-record-ids-switch.test.ts create mode 100644 packages/plugins/plugin-sharing/src/shared-record-ids.testkit.ts create mode 100644 scripts/adr-anchors/packages__plugins__plugin-sharing__src__share-arm-boot.ts.json create mode 100644 scripts/adr-anchors/packages__plugins__plugin-sharing__src__sharing-service.ts.json diff --git a/.changeset/33787-shared-record-ids-switch.md b/.changeset/33787-shared-record-ids-switch.md new file mode 100644 index 00000000000..2537ce23b0a --- /dev/null +++ b/.changeset/33787-shared-record-ids-switch.md @@ -0,0 +1,31 @@ +--- +'@objectstack/plugin-sharing': patch +'@objectstack/plugin-security': patch +--- + +fix(plugin-sharing)!: every share grant counts; the sharing scopes carry the share-grant leaf instead of a list capped at 5,000 grants (ADR-0155 plan step 6) + +Clause-②: yes (narrowing) +Metadata-protocol: none + + + +**What was wrong.** The read scope of a sharing-scoped object read the caller's share grants into an id list first, at most 5,000 of them, and dropped the rest without a word: a member holding 6,000 grants on one object saw 6,000 rows of 7,000 (1,000 owned plus 5,000 of the 6,000 shared), and a GET of an unread grant answered 404. The predicate-update scope had the same cap on edit-level grants. + +**Now.** `buildReadFilter` and `buildWriteFilter` carry the share arm as the share-grant leaf, `{ id: { $in: SharedRecordIds.read(object, user) } }` (the update scope carries `.write(object, user, ['edit', 'full'])`), which the SQL driver compiles as a subquery over `sys_record_share` inside the same statement. Every grant counts, at any number; no grant is read into memory and nothing binds one parameter per grant. The pending-approval ids stand as a disjunct of their own. `delete` scopes to the owner match alone, as before. + +**BREAKING**, in three places, each a tightening that lands here, where it takes effect: + +- **Share grants stop counting on objects whose storage cannot evaluate them** (ADR-0155 R2). An object stored on another datasource than `sys_record_share`, or by a driver that does not evaluate the leaf (`supports.fixedReadLeaves` without `SharedRecordIds`: today the MongoDB, in-memory and OData drivers), keeps its owner, queue and pending-approval access unchanged, but its share rows are no longer consulted: no scope carries the share arm, the edit gate reads no grant, and a new grant or a new sharing rule on it is refused `SHARING_NOT_ENABLED` (422 at the REST doors). The boot names, once at `warn`, every such object that holds `sys_record_share` rows, with the reason. `security/explain` reports each share on such a record as evaluated and not granting, and says why. + The fix for a host: to share such an object's records again, store it on the datasource of `sys_record_share`, on a driver that evaluates share grants (the SQL drivers do). +- **A narrowing of `sys_record_share` reads registered BY NAME refuses the boot** (ADR-0155 R1 at boot, D4). A host that registers an object-scoped middleware, or a `beforeFind` / `afterFind` hook, for `sys_record_share` (an opt-in of that table into plugin-audit's record-view auditing included) no longer starts: the boot fails at `kernel:bootstrapped`, before any request is served, with `INTERNAL_ERROR` / 500 naming the registration. No registration is exempt, one whose handler skips system reads included. A registration made after boot is refused at read by the engine, with the same envelope. + The fix for a host: remove that registration for `sys_record_share`. A host that opted the table into record-view auditing gives up that auditing of share rows. +- **A narrowing that names NO object is not run on the share arm.** A middleware or a find hook registered for no object, or for `'*'`, ran on today's grant read, which went through the engine as a system read. The share arm now makes no engine read of `sys_record_share`, so such a registration does not run on it, and nothing refuses, reports or logs that. On a host where such a registration changes a system read of `sys_record_share`, the share arm's rows can differ from what they were. This paragraph is the telling (ADR-0155 D4's boundary; `ISharingService`'s contract says the same). The repository's own registrations of that kind were read before this change, and none changes that read. + +**Preconditions this step inherits from the PostgreSQL key-type change** (ADR-0155 O2): + +1. On PostgreSQL, a statement holding the leaf whose catalog read fails, or finds no such relation, answers `INTERNAL_ERROR` / 500, where an uncast statement would have run. +2. Each transaction pays one savepoint and one catalog read per table it compares a leaf against, when the table has no pooled reading. +3. A failed catalog read inside that savepoint rolls back the caller's concurrent statements on the same transaction. The sharing plugin issues no statement of its own that carries the leaf, and none of its reads runs inside a caller's transaction or concurrently with another on one: its own reads are sequential system reads. + +**What it costs, quoted no wider than ADR-0155 quotes it.** For the scope statements alone (an account page, its total and the two grant reads), at 1M rows and 5,000 grants, the id-list scope against the subquery scope read PostgreSQL 21.6 → 7.0 ms and SQLite 18.3 → 12.1 ms. It is not a whole-request figure. For a caller holding no grant, whose scope was the bare owner match and is now an `$or` with the subquery, SQLite still serves the page and its total from the owner index; PostgreSQL 16 serves the page as before but plans the total as a sequential scan, which grows with the table. diff --git a/packages/plugins/plugin-security/src/controlled-by-parent-leaf-switch.test.ts b/packages/plugins/plugin-security/src/controlled-by-parent-leaf-switch.test.ts index 590a0731ebd..a709d5597f9 100644 --- a/packages/plugins/plugin-security/src/controlled-by-parent-leaf-switch.test.ts +++ b/packages/plugins/plugin-security/src/controlled-by-parent-leaf-switch.test.ts @@ -601,7 +601,10 @@ for (const cell of CELLS) describe(`on ${cell.label}`, () => { }); const reads = statements.filter(readsTable(`${DEEP}_2`)); expect(reads, statements.join('\n')).toHaveLength(1); - expect(reads[0].match(/in \(select/gi) ?? []).toHaveLength(8); + expect(reads[0].match(/in \(select .id. from/gi) ?? []).toHaveLength(8); + // [ADR-0155 plan step 6] The root's share arm rides inside the innermost + // scope as the share-grant semi-join, the statement's ninth subquery. + expect(reads[0].match(/in \(select .record_id. from .sys_record_share./gi) ?? []).toHaveLength(1); expect(await rig.read(`${DEEP}_${DEEP_LINKS - 1}`, context)).toEqual([`${DEEP}_${DEEP_LINKS - 1}_r`]); }); }); diff --git a/packages/plugins/plugin-security/src/controlled-by-parent-sharing.test.ts b/packages/plugins/plugin-security/src/controlled-by-parent-sharing.test.ts index b4301ec058b..6f937f333f9 100644 --- a/packages/plugins/plugin-security/src/controlled-by-parent-sharing.test.ts +++ b/packages/plugins/plugin-security/src/controlled-by-parent-sharing.test.ts @@ -540,8 +540,11 @@ describe('[#5386] controlled_by_parent folds the master\'s ownership and share g userId: REP, tenantId: 'org-1', } as any); + // [ADR-0155 plan step 6] Its share arm is the share-grant leaf; the + // testkit evaluates it over the double's share rows, as a driver does. + const masterWhere = await h.compose(masterFilter, { userId: REP, tenantId: 'org-1' }); const directlyReadable = (h.store.rows.crm_account ?? []) - .filter((r) => matchesFilterCondition(r, masterFilter as any)) + .filter((r) => matchesFilterCondition(r, masterWhere as any)) .map((r) => String(r.id)); expect(directlyReadable).toEqual(['acct_us', 'acct_own']); }); @@ -581,7 +584,7 @@ describe('[#5386] controlled_by_parent folds the master\'s ownership and share g }); // ── boundary conditions ────────────────────────────────────────────────── - it('the derivation does NO store work; the grant table is read when the master\'s scope is composed, and the detail is never re-entered', async () => { + it('the derivation does NO store work; the master\'s share arm is answered inside the composition, and the detail is never re-entered', async () => { const h = await boot({ shareLevel: 'edit' }); h.store.find.mockClear(); // [ADR-0139 D6] The middleware writes the leaf and walks the chain over @@ -590,15 +593,19 @@ describe('[#5386] controlled_by_parent folds the master\'s ownership and share g const during = h.store.find.mock.calls.map((c: any[]) => String(c[0])); expect(during).not.toContain('crm_account'); expect(during).not.toContain('crm_contact'); - // The master's scope is composed by the engine (here, by the testkit): - // THAT is where the grant table is consulted — direct evidence the sharing - // half runs inside the composition and not merely that some filter came - // back — and the detail itself is never read to answer its own scope. - await h.compose(injected, h.repContext()); + // The master's scope is composed by the engine (here, by the testkit), + // and the detail itself is never read to answer its own scope. + // [ADR-0155 plan step 6] The master's share arm is the share-grant leaf, + // evaluated inside the composed statement: no grant row is read on its + // own. `acct_us`, which the rep reaches only through its grant, in the + // composed set is the direct evidence the sharing half ran inside the + // composition and not merely that some filter came back. + const composed = await h.compose(injected, h.repContext()); const reads = h.store.find.mock.calls.map((c: any[]) => String(c[0])); - expect(reads).toContain('sys_record_share'); + expect(reads).not.toContain('sys_record_share'); expect(reads).not.toContain('crm_account'); expect(reads).not.toContain('crm_contact'); + expect(JSON.stringify(composed)).toContain('acct_us'); }); it('a deployment WITHOUT plugin-sharing is unchanged — RLS-only derivation, nothing to fold', async () => { @@ -704,13 +711,16 @@ describe('[#5815] getReadFilter enforces the same read scope as the engine middl expect(before).not.toContain('crm_account'); expect(before).not.toContain('crm_contact'); // Composing the leaf asks `getReadFilter(account)`, whose sharing half - // reads the grant table — direct evidence the derivation runs on THIS - // path rather than a filter merely coming back from somewhere. + // carries the share-grant leaf (ADR-0155 plan step 6), evaluated inside + // the composed statement: `acct_us`, reached only through its grant, in + // the composed set is direct evidence the derivation runs on THIS path + // rather than a filter merely coming back from somewhere. h.store.find.mockClear(); - await h.compose(filter ?? null, h.repContext()); + const composed = await h.compose(filter ?? null, h.repContext()); const reads = h.store.find.mock.calls.map((c: any[]) => String(c[0])); - expect(reads).toContain('sys_record_share'); + expect(reads).not.toContain('sys_record_share'); expect(reads).not.toContain('crm_contact'); + expect(JSON.stringify(composed)).toContain('acct_us'); }); it('a delegated (on-behalf-of) read whose delegator does not exist still denies outright — unchanged by the added layer', async () => { diff --git a/packages/plugins/plugin-security/src/explain-dependency-fault.test.ts b/packages/plugins/plugin-security/src/explain-dependency-fault.test.ts index 9954ad48b25..f475f2dac52 100644 --- a/packages/plugins/plugin-security/src/explain-dependency-fault.test.ts +++ b/packages/plugins/plugin-security/src/explain-dependency-fault.test.ts @@ -32,6 +32,7 @@ import { SharingService, buildSharingMiddleware } from '@objectstack/plugin-shar import { PermissionSetSchema } from '@objectstack/spec/security'; import type { PermissionSet } from '@objectstack/spec/security'; import { SecurityPlugin } from './security-plugin.js'; +import { resolveFixedReadLeavesInMemory } from './shared-record-ids-in-memory.testkit.js'; import { defaultPermissionSets } from './objects/default-permission-sets.js'; // ── metadata ─────────────────────────────────────────────────────────────── @@ -157,7 +158,11 @@ function makeEngine(schema: Record, storeFaults: ReadonlyMap (name === OBJECT ? schema : undefined), async find(object: string, options: any = {}) { const rows = (tables[object] ??= []); - const hits = rows.filter((r) => matches(r, options.filter ?? options.where)); + // [ADR-0155 plan step 6] The share-grant leaf, resolved once for the + // statement as the driver's semi-join is: with the share store down, the + // statement fails on that fault, whichever arm the row would match. + const where = resolveFixedReadLeavesInMemory(options.filter ?? options.where, (table) => tables[table]); + const hits = rows.filter((r) => matches(r, where)); return typeof options.limit === 'number' ? hits.slice(0, options.limit) : hits; }, async findOne(object: string, options: any = {}) { @@ -317,6 +322,10 @@ function expectNotEvaluated(decision: any, layer: string): void { // ─────────────────────────────────────────────────────────────────────────── describe("plugin-sharing's read filter rejects — explain(read) fails closed", () => { + // [ADR-0155 plan step 6] With the share store down, the read filter itself + // now answers (it reads no grant row: its share arm is the share-grant leaf); + // the fault surfaces where the leaf is evaluated, in the find's statement and + // in explain's read of the leaf at the record, and both fail on it. const rows: RowKey[] = ['unshared', 'shared', 'owned']; it.each(rows)('the share store is down × %s row: not visible, and the find fails on the same fault', async (rowKey) => { const stack = await makeStack({ storeFaults: ['sys_record_share'] }); diff --git a/packages/plugins/plugin-security/src/explain-engine.ts b/packages/plugins/plugin-security/src/explain-engine.ts index 8001b415448..d5d51356624 100644 --- a/packages/plugins/plugin-security/src/explain-engine.ts +++ b/packages/plugins/plugin-security/src/explain-engine.ts @@ -238,6 +238,32 @@ function isDenyAll(filter: unknown): boolean { return isDenyAllSentinel(filter) || isRlsDenySentinel(filter); } +/** + * [ADR-0155 ② ruled R2] The sharing service's verdict on whether share grants + * count on `object`, read through the deps bag: a reason, or `undefined` when + * they count, when the bag carries no reader, or when the reader throws (no + * answer is never a reason). + */ +function shareGrantsInertReasonOf(deps: Pick, object: string): string | undefined { + if (typeof deps.shareGrantsInertReason !== 'function') return undefined; + try { + const reason = deps.shareGrantsInertReason(object); + return typeof reason === 'string' && reason !== '' ? reason : undefined; + } catch { + return undefined; + } +} + +/** + * [ADR-0155 ② ruled R2] The explainer's sentence: the sharing layer's detail, + * followed by why the shares attached to the record admit nothing, when share + * grants do not count on its object. + */ +function withSharesInertSentence(reason: string | undefined, detail: string): string { + if (reason === undefined) return detail; + return `${detail} Share grants do not count on this object, so no share attached to the record is consulted: ${reason}.`; +} + /** * A dependency call that REJECTED, kept apart from every value it could have * resolved to. @@ -504,6 +530,16 @@ export interface ExplainEngineDeps { recordId: string, context: any, ) => Promise>; + /** + * [ADR-0155 ② ruled R2] Why share grants do not count on the object, or + * `null` when they do: the sharing service's own verdict + * (`SharingService.shareGrantsInertReason`), the one its read scope, its + * write gate and its grant doors read. Where it names a reason, every share + * attached to the record is reported `neutral` and the sharing layer's + * detail says why. Optional: a deps bag wired without it reports shares as + * before; a throw counts as no answer. + */ + shareGrantsInertReason?: (object: string) => string | null | undefined; /** * [#26180] The pending approval requests that grant the principal READ of * the record while their step is pending (`SharingService.listApprovalReadGrants`, @@ -2080,8 +2116,13 @@ async function applyRecordAttribution( const shares = deps.listRecordShares && recordExists ? await deps.listRecordShares(object, recordId, context).catch(() => []) : []; + // [ADR-0155 ② ruled R2] On an object whose storage does not evaluate the + // share arm, no share row is consulted: each is evaluated and `neutral`, and + // the layer's detail carries the sentence below. + const sharesInertReason = (shares ?? []).length > 0 ? shareGrantsInertReasonOf(deps, object) : undefined; const shareRules: ExplainMatchedRule[] = (shares ?? []).map((s) => { - const recipMatchesUser = s.recipient_type === 'user' && s.recipient_id != null && String(s.recipient_id) === String(context?.userId); + const recipMatchesUser = sharesInertReason === undefined + && s.recipient_type === 'user' && s.recipient_id != null && String(s.recipient_id) === String(context?.userId); const kind: ExplainMatchedRule['kind'] = s.source === 'rule' ? 'sharing_rule' : s.source === 'team' ? 'team' : 'record_share'; return { @@ -2354,7 +2395,7 @@ async function applyRecordAttribution( rules: shareRules, // A fault is only ever recorded against an existing record, and the // master leg [ADR-0055] is only ever asked of one. - detail: sharingFaultDetail ?? masterLegRefusal?.detail ?? masterReadNullArmAdmits ?? (!recordExists + detail: withSharesInertSentence(sharesInertReason, sharingFaultDetail ?? masterLegRefusal?.detail ?? masterReadNullArmAdmits ?? (!recordExists ? 'Record not found; sharing not evaluated.' : owd.effect !== 'private' ? 'Baseline is not private — sharing adds nothing beyond it for this record.' @@ -2396,7 +2437,7 @@ async function applyRecordAttribution( : `${shareRules.length} share(s) attached; none grants the caller access to this record.` + (vamaEffective ? ` Superseded by the View/Modify All Data bypass [${vamaSets.join(', ')}] — see the vama_bypass layer.` - : '')), + : ''))), }; } diff --git a/packages/plugins/plugin-security/src/explain-fixed-read-leaf.test.ts b/packages/plugins/plugin-security/src/explain-fixed-read-leaf.test.ts index df9900eab37..f2478d3cf1b 100644 --- a/packages/plugins/plugin-security/src/explain-fixed-read-leaf.test.ts +++ b/packages/plugins/plugin-security/src/explain-fixed-read-leaf.test.ts @@ -7,9 +7,8 @@ // shapes today's filter has for a caller with one grant on the record (`[id]`) // and with none (the share arm left out), and ⛔ never carries the leaf. // -// The sharing service's read filter is replaced here by the shape the step-6 -// producer writes, `{ $or: [owner match, { id: { $in: leaf } }] }`: no producer -// on main writes the leaf yet (plugin-sharing is untouched on this card). The +// The sharing service's read filter is the step-6 producer's own, +// `{ $or: [owner match, { id: { $in: leaf } }] }` (ADR-0155 plan step 6). The // rest is the real SecurityPlugin and the real SharingService, over an engine // double that records its reads. import { describe, it, expect, vi } from 'vitest'; @@ -45,7 +44,8 @@ const SHARE_ROWS = [ { id: 's3', object_name: OBJECT, record_id: UNSHARED, recipient_type: 'user', recipient_id: 'u_other', access_level: 'read' }, ]; -function makeEngine() { +/** `legacy`: the object is stored by a driver that does not evaluate share grants (ADR-0155 R2). */ +function makeEngine(storage: 'sql' | 'legacy' = 'sql') { const tables: Record = { [OBJECT]: [row(SHARED), row(UNSHARED)], sys_record_share: SHARE_ROWS.map((r) => ({ ...r })), @@ -71,6 +71,9 @@ function makeEngine() { _middlewares: [] as any[], registerMiddleware(mw: any) { this._middlewares.push(mw); }, getSchema: (name: string) => (name === OBJECT ? SCHEMA : undefined), + getDriverForObject: () => (storage === 'legacy' + ? { name: 'legacy', supports: {} } + : { name: 'sql', supports: { fixedReadLeaves: ['SharedRecordIds'] } }), async find(object: string, options: any = {}) { reads.push({ object, where: options.where }); const hits = (tables[object] ?? []).filter((r) => matches(r, options.filter ?? options.where)); @@ -83,8 +86,8 @@ function makeEngine() { }; } -async function makeStack() { - const engine = makeEngine(); +async function makeStack(storage: 'sql' | 'legacy' = 'sql') { + const engine = makeEngine(storage); let security: any; let sharing: SharingService; const errors: string[] = []; @@ -106,9 +109,6 @@ async function makeStack() { await plugin.init(ctx); await plugin.start(ctx); sharing = new SharingService({ engine: engine as any, securityService: () => security }); - // The step-6 producer's shape (see the header): the owner match OR the leaf. - (sharing as any).buildReadFilter = async (object: string, context: any) => - ({ $or: [{ owner_id: context.userId }, { id: { $in: SharedRecordIds.read(object, context.userId) } }] }); const explain = (operation: 'read' | 'update', target: { recordId?: string; recordIds?: string[] }) => security.explain({ object: OBJECT, operation, ...target }, { ...READER_CTX }); return { engine, explain, errors, sharing }; @@ -229,3 +229,27 @@ describe('[ADR-0155 Q2] the explainer resolves the share-grant leaf at the recor expect(sharingLayer(decision).record.rowFilter).toBeUndefined(); }); }); + +describe('[ADR-0155 ② ruled R2] the explainer says why a share on the record admits nothing', () => { + it('on an object whose storage does not evaluate share grants: the shares are neutral, the record is excluded, and the detail names the reason', async () => { + const { engine, explain } = await makeStack('legacy'); + const decision = await explain('read', { recordId: SHARED }); + const record = sharingLayer(decision).record; + // The scope carries no share arm there, so nothing of the leaf is resolved. + expect(record.rowFilter).toEqual({ owner_id: U_READER }); + expect(record.matchesRecord).toBe(false); + expect(decision.record).toMatchObject({ recordId: SHARED, visible: false }); + const shares = record.rules.filter((r: any) => r.kind === 'record_share'); + expect(shares.map((r: any) => r.effect)).toEqual(['neutral', 'neutral']); + expect(record.detail).toContain('Share grants do not count on this object, so no share attached to the record is consulted'); + expect(record.detail).toContain("stored by driver 'legacy'"); + expect(shareReads(engine).some((r) => JSON.stringify(r.where).includes('"recipient_id"'))).toBe(false); + }); + + it('CONTROL: where they count, the same shares admit the caller and no sentence is added', async () => { + const { explain } = await makeStack('sql'); + const record = sharingLayer(await explain('read', { recordId: SHARED })).record; + expect(record.rules.filter((r: any) => r.kind === 'record_share').map((r: any) => r.effect)).toEqual(['admits', 'admits']); + expect(record.detail).not.toContain('Share grants do not count'); + }); +}); diff --git a/packages/plugins/plugin-security/src/explain-read-verdict-inputs.test.ts b/packages/plugins/plugin-security/src/explain-read-verdict-inputs.test.ts index ddf752e7fca..b698f2ada3f 100644 --- a/packages/plugins/plugin-security/src/explain-read-verdict-inputs.test.ts +++ b/packages/plugins/plugin-security/src/explain-read-verdict-inputs.test.ts @@ -26,6 +26,7 @@ import { SharingService, buildSharingMiddleware } from '@objectstack/plugin-shar import { PermissionSetSchema } from '@objectstack/spec/security'; import type { PermissionSet } from '@objectstack/spec/security'; import { SecurityPlugin } from './security-plugin.js'; +import { resolveFixedReadLeavesInMemory } from './shared-record-ids-in-memory.testkit.js'; import { defaultPermissionSets } from './objects/default-permission-sets.js'; // ── metadata ─────────────────────────────────────────────────────────────── @@ -161,7 +162,9 @@ function makeEngine(schema: Record) { getSchema: (name: string) => (name === OBJECT ? schema : undefined), async find(object: string, options: any = {}) { const rows = (tables[object] ??= []); - return rows.filter((r) => matches(r, options.filter ?? options.where)).slice(0, options.limit ?? 1000); + // [ADR-0155 plan step 6] The share-grant leaf, resolved once for the statement. + const where = resolveFixedReadLeavesInMemory(options.filter ?? options.where, (table) => tables[table]); + return rows.filter((r) => matches(r, where)).slice(0, options.limit ?? 1000); }, async findOne(object: string, options: any = {}) { assertEngineFindOnePredicate(object, options); diff --git a/packages/plugins/plugin-security/src/readable-ids-in-memory.testkit.ts b/packages/plugins/plugin-security/src/readable-ids-in-memory.testkit.ts index 5f8ed411fb0..3f29bc84e70 100644 --- a/packages/plugins/plugin-security/src/readable-ids-in-memory.testkit.ts +++ b/packages/plugins/plugin-security/src/readable-ids-in-memory.testkit.ts @@ -27,6 +27,11 @@ * 4. a parent the double holds no rows for answers `$in: []`, as a parent * the registry does not hold does in the engine. * + * A share-grant leaf (`SharedRecordIds`, ADR-0155) in any scope, P's own or + * the read's, is replaced by its members over the double's share rows + * (`shared-record-ids-in-memory.testkit.ts`), as the driver's semi-join + * evaluates it inside the one statement. + * * ⛔ Not a second composer for production: D5's two classes (a master on * another datasource, a master an object-scoped read middleware narrows) are * refused at boot and are not modelled; the tenant wall is the driver's and a @@ -38,8 +43,9 @@ * the master's scope answered by the real security service. */ -import { RLS_DENY_FILTER, isComposedReadableIds, isReadableIds } from '@objectstack/spec/data'; +import { RLS_DENY_FILTER, isComposedReadableIds, isFixedReadLeaf, isReadableIds } from '@objectstack/spec/data'; import { matchesFilterCondition } from '@objectstack/formula'; +import { fixedReadLeafMembers } from './shared-record-ids-in-memory.testkit.js'; /** The engine's `READABLE_IDS_MAX_CHAIN_DEPTH`: scopes composed above the read's own `where`. */ const MAX_CHAIN_DEPTH = 8; @@ -128,7 +134,11 @@ export async function composeReadableIdsInMemory( const item = (value as Record)[key]; const next = key === '$in' && isReadableIds(item) ? await resolve(item.object, ancestors) - : await rewrite(item, ancestors); + : key === '$in' && isFixedReadLeaf(item) + // [ADR-0155 plan step 6] The share arm of a scope, P's own or the + // read's: the leaf's members over the double's share rows. + ? fixedReadLeafMembers(item, security.rows) + : await rewrite(item, ancestors); if (next !== item) (out ??= { ...(value as Record) })[key] = next; } return out ?? value; diff --git a/packages/plugins/plugin-security/src/readable-ids-nested-compose.test.ts b/packages/plugins/plugin-security/src/readable-ids-nested-compose.test.ts index e40a545218c..862419d849e 100644 --- a/packages/plugins/plugin-security/src/readable-ids-nested-compose.test.ts +++ b/packages/plugins/plugin-security/src/readable-ids-nested-compose.test.ts @@ -412,14 +412,18 @@ describe('[ADR-0139 D6 as amended] a two-level controlled_by_parent chain compos // and the grandparent inside that one. const reads = statements.filter(readsTable(child)); expect(reads, all).toHaveLength(1); - expect(reads[0].match(/in \(select/gi) ?? [], all).toHaveLength(2); + expect(reads[0].match(/in \(select .id. from/gi) ?? [], all).toHaveLength(2); expect(reads[0], all).toMatch(new RegExp(`in \\(select .id. from .${PARENT}. where .grand. in \\(select .id. from .${GRAND}.`, 'i')); + // [ADR-0155 plan step 6] …and the grandparent's share arm inside that + // one, as the share-grant semi-join: the third subquery of the statement. + expect(reads[0].match(/in \(select .record_id. from .sys_record_share./gi) ?? [], all).toHaveLength(1); // No statement reads the parent or the grandparent on its own: the // leaf stands where the pre-resolved id list stood at every level, so - // neither is pre-scanned. What else the driver ran is plugin-sharing - // reading the share rows to answer the grandparent's scope. + // neither is pre-scanned. Nor the share rows: the grandparent's scope + // carries them as the semi-join above, never as a read of their own. expect(statements.filter(readsTable(PARENT)), all).toHaveLength(0); expect(statements.filter(readsTable(GRAND)), all).toHaveLength(0); + expect(statements.filter(readsTable('sys_record_share')), all).toHaveLength(0); } } }); diff --git a/packages/plugins/plugin-security/src/security-plugin-explain-access.ts b/packages/plugins/plugin-security/src/security-plugin-explain-access.ts index c9e12d81d36..2e71b7fb1fe 100644 --- a/packages/plugins/plugin-security/src/security-plugin-explain-access.ts +++ b/packages/plugins/plugin-security/src/security-plugin-explain-access.ts @@ -516,6 +516,11 @@ export async function explainAccessForCaller( // manager — the exact behaviour this binding had before the gate. ? { listRecordShares: (o: string, rid: string) => sharing.listShares(o, rid, { isSystem: true }) } : {}), + // [ADR-0155 ② ruled R2] Whether share grants count on the object at all: + // the sharing service's own verdict, asked of it, never restated here. + ...(sharing && typeof sharing.shareGrantsInertReason === 'function' + ? { shareGrantsInertReason: (o: string) => sharing.shareGrantsInertReason(o) } + : {}), // [#26180] The pending approval requests that grant the EXPLAINED // principal read of the record — the same answer the sharing read filter // ORs in, asked with the explained context, so the attribution names the diff --git a/packages/plugins/plugin-security/src/shared-record-ids-in-memory.testkit.ts b/packages/plugins/plugin-security/src/shared-record-ids-in-memory.testkit.ts new file mode 100644 index 00000000000..e69732b99ac --- /dev/null +++ b/packages/plugins/plugin-security/src/shared-record-ids-in-memory.testkit.ts @@ -0,0 +1,77 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 plan step 6] The share-grant leaf for this package's engine + * doubles. + * + * From the switch on, plugin-sharing's read and bulk-write scopes carry the + * share arm as `{ id: { $in: SharedRecordIds.read(object, user) } }` (or + * `.write`), a branded leaf where an id list used to be. A double whose `$in` + * arm calls `.includes` on its comparand cannot read it, and an evaluator such + * as `matchesFilterCondition` reads it as a list with no member, which greens + * a scope that admits nothing. So a double resolves it here, over its OWN + * `sys_record_share` rows, under the leaf's own fixed inner read + * (`fixedInnerReadOf`): the predicate is the leaf's description, ⛔ never + * restated in a test. + * + * Resolved once per statement, before any row is matched, as a driver's + * semi-join is part of the one statement: a double whose share table is down + * (its rows' `filter` throws) fails the statement on that fault, whichever arm + * a row would have matched. A leaf anywhere but an `$in` comparand is one the + * engine refuses, and throws here. + * + * `.testkit.ts`, not `.test.ts`: it holds no assertions and is not collected + * as a suite, and it is imported only by tests. + */ + +import { fixedInnerReadOf, isFixedReadLeaf, type FixedReadLeaf } from '@objectstack/spec/data'; + +/** A row as the doubles store it. */ +type Row = Record; + +/** The rows a double holds for `table`, or `undefined` for one it does not hold. */ +export type InMemoryRowsOf = (table: string) => readonly Row[] | undefined; + +/** + * The ids `leaf`'s fixed inner read denotes over the double's rows: every row + * of its table whose `equals` columns match and whose `memberOf` columns hold + * one of the listed values, its projected column kept when it is neither null + * nor empty, as each evaluator keeps it. + */ +export function fixedReadLeafMembers(leaf: FixedReadLeaf, rowsOf: InMemoryRowsOf): string[] { + const read = fixedInnerReadOf(leaf); + const held = (rowsOf(read.table) ?? []).filter((row) => + Object.entries(read.equals).every(([column, value]) => row[column] === value) + && Object.entries(read.memberOf).every(([column, values]) => values.includes(String(row[column])))); + return held.map((row) => row[read.column]).filter((id) => id != null && id !== '').map(String); +} + +/** + * `where` with every `$in` comparand that is a fixed-read leaf replaced by its + * members, copy-on-write: a subtree holding no leaf is returned by reference. + */ +export function resolveFixedReadLeavesInMemory(where: T, rowsOf: InMemoryRowsOf): T { + const walk = (value: unknown, underIn: boolean): unknown => { + if (isFixedReadLeaf(value)) { + if (!underIn) throw new TypeError('test double: a fixed-read leaf outside an `$in` comparand (the engine refuses it)'); + return fixedReadLeafMembers(value, rowsOf); + } + if (value === null || typeof value !== 'object') return value; + if (Array.isArray(value)) { + let out: unknown[] | undefined; + value.forEach((item, i) => { + const next = walk(item, false); + if (next !== item) (out ??= [...value])[i] = next; + }); + return out ?? value; + } + let out: Row | undefined; + for (const key of Object.keys(value)) { + const item = (value as Row)[key]; + const next = walk(item, key === '$in'); + if (next !== item) (out ??= { ...(value as Row) })[key] = next; + } + return out ?? value; + }; + return walk(where, false) as T; +} diff --git a/packages/plugins/plugin-sharing/src/authored-row-write-deferral.test.ts b/packages/plugins/plugin-sharing/src/authored-row-write-deferral.test.ts index 06e0c2b920c..417b722e3af 100644 --- a/packages/plugins/plugin-sharing/src/authored-row-write-deferral.test.ts +++ b/packages/plugins/plugin-sharing/src/authored-row-write-deferral.test.ts @@ -62,6 +62,9 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFin import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; import { SharingService, type SharingSecurityProbe } from './sharing-service.js'; import { buildSharingMiddleware } from './sharing-plugin.js'; +import { SharedRecordIds } from '@objectstack/spec/data'; +import { WRITE_ACCESS_LEVELS } from './access-level.js'; +import { inMembers } from './shared-record-ids.testkit.js'; // ── metadata ─────────────────────────────────────────────────────────────── @@ -197,7 +200,8 @@ function makeEngine() { for (const [k, v] of Object.entries(filter)) { if (k === '$or' || k === '$and') continue; if (v != null && typeof v === 'object' && '$in' in (v as any)) { - if (!(v as any).$in.includes(row[k])) return false; + // [ADR-0155] A share-grant leaf resolves over this double's own share rows. + if (!inMembers((v as any).$in, tables.sys_record_share).includes(row[k])) return false; continue; } if (row[k] !== v) return false; @@ -649,8 +653,11 @@ describe('[#5493 / #6736] the BULK path is untouched — a verdict is a by-id an let nextCalled = false; await stack.mw(opCtx, async () => { nextCalled = true; }); expect(nextCalled, 'the bulk branch scopes rather than refuses').toBe(true); - expect(opCtx.ast.where, 'still scoped by OWNERSHIP, unwidened by any authored policy') - .toEqual({ $and: [{ stage: 'prospecting' }, { owner_id: U_WIDENED }] }); + expect(opCtx.ast.where, 'still scoped by OWNERSHIP and edit-shares, unwidened by any authored policy') + .toEqual({ $and: [{ stage: 'prospecting' }, { $or: [ + { owner_id: U_WIDENED }, + { id: { $in: SharedRecordIds.write('crm_campaign', U_WIDENED, WRITE_ACCESS_LEVELS) } }, + ] }] }); expect(stack.security!.calls, 'the bulk path asks no verdict').toEqual([]); }); }); diff --git a/packages/plugins/plugin-sharing/src/external-owd-floor.test.ts b/packages/plugins/plugin-sharing/src/external-owd-floor.test.ts index b10ebca5b97..b045e38c818 100644 --- a/packages/plugins/plugin-sharing/src/external-owd-floor.test.ts +++ b/packages/plugins/plugin-sharing/src/external-owd-floor.test.ts @@ -13,7 +13,10 @@ import { describe, it, expect, beforeEach } from 'vitest'; import { EXTERNAL_READ_GRANT_KEY, EXTERNAL_WRITE_GRANT_KEY } from '@objectstack/core'; +import { SharedRecordIds } from '@objectstack/spec/data'; import { SharingService } from './sharing-service.js'; +import { WRITE_ACCESS_LEVELS } from './access-level.js'; +import { inMembers } from './shared-record-ids.testkit.js'; type Row = Record; @@ -75,9 +78,11 @@ describe('the EXTERNAL OWD floor — reads', () => { } it('a share reaches the external on a public_read_write object (OR-ed beside the owner arm)', async () => { - expect(await svc.buildReadFilter('board', { ...EXTERNAL } as any)).toEqual({ - $or: [{ owner_id: 'u_ext' }, { id: { $in: ['b_shared'] } }], + const f: any = await svc.buildReadFilter('board', { ...EXTERNAL } as any); + expect(f).toEqual({ + $or: [{ owner_id: 'u_ext' }, { id: { $in: SharedRecordIds.read('board', 'u_ext') } }], }); + expect(inMembers(f.$or[1].id.$in, TABLES().sys_record_share)).toEqual(['b_shared']); }); it('either carried value floors it: audience alone, or the EXTERNAL rung alone', async () => { @@ -102,7 +107,9 @@ describe('the EXTERNAL OWD floor — reads', () => { }); it('private stays owner ∪ shares, as for a member', async () => { - expect(await svc.buildReadFilter('private_doc', { ...EXTERNAL } as any)).toEqual({ owner_id: 'u_ext' }); + expect(await svc.buildReadFilter('private_doc', { ...EXTERNAL } as any)).toEqual({ + $or: [{ owner_id: 'u_ext' }, { id: { $in: SharedRecordIds.read('private_doc', 'u_ext') } }], + }); }); it('an object with no owner column is not under OWD: the sharing layer abstains, for an external as for a member', async () => { @@ -123,9 +130,11 @@ describe('the EXTERNAL OWD floor — writes', () => { }); it('bulk writes on public_read_write are owner ∪ edit-shares for an external, open for a member', async () => { - expect(await svc.buildWriteFilter('board', { ...EXTERNAL } as any, 'update')).toEqual({ - $or: [{ owner_id: 'u_ext' }, { id: { $in: ['b_shared'] } }], + const update: any = await svc.buildWriteFilter('board', { ...EXTERNAL } as any, 'update'); + expect(update).toEqual({ + $or: [{ owner_id: 'u_ext' }, { id: { $in: SharedRecordIds.write('board', 'u_ext', WRITE_ACCESS_LEVELS) } }], }); + expect(inMembers(update.$or[1].id.$in, TABLES().sys_record_share)).toEqual(['b_shared']); expect(await svc.buildWriteFilter('board', { ...EXTERNAL } as any, 'delete')).toEqual({ owner_id: 'u_ext' }); expect(await svc.buildWriteFilter('board', { ...MEMBER } as any, 'update')).toBeNull(); }); diff --git a/packages/plugins/plugin-sharing/src/federated-phantom-owner-scoping.test.ts b/packages/plugins/plugin-sharing/src/federated-phantom-owner-scoping.test.ts index 1043eef34a9..e411a1158b0 100644 --- a/packages/plugins/plugin-sharing/src/federated-phantom-owner-scoping.test.ts +++ b/packages/plugins/plugin-sharing/src/federated-phantom-owner-scoping.test.ts @@ -62,6 +62,8 @@ import { PHANTOM_ANCHOR_WRITE_DENY_NOTICE, UNSERVED_OWNER_WRITE_DENY_NOTICE, } from './sharing-service.js'; +import { SharedRecordIds } from '@objectstack/spec/data'; +import { inMembers } from './shared-record-ids.testkit.js'; /** The caller: an ordinary member whose read/write DEPTH is narrower than `org`. */ const MEMBER = 'usr_member_1'; @@ -147,22 +149,27 @@ function makeEngine( tables: Record>> = {}, ) { /** - * Match one row against a `where` bag. Handles exactly the two shapes this - * service composes — primitive equality and `{ $in: [...] }` — and THROWS on + * Match one row against a `where` bag. Handles exactly the shapes this + * service composes — primitive equality, `{ $in: [...] }`, `$or` (conjoined + * with its sibling keys), and [ADR-0155] `{ $in: }`, + * resolved over this double's own `sys_record_share` rows — and THROWS on * anything else rather than ignoring it. An unrecognised operator silently * skipped would make the double strictly more permissive than the engine, and * a fixture that over-matches is how a share lookup "finds" a grant that the * real store would not have returned. */ - const matches = (row: Record, where: Record) => + const matches = (row: Record, where: Record): boolean => Object.entries(where).every(([key, cond]) => { + if (key === '$or' && Array.isArray(cond)) { + return cond.some((branch) => matches(row, branch as Record)); + } if (key.startsWith('$')) throw new Error(`fake engine: unsupported operator ${key}`); if (cond !== null && typeof cond === 'object' && !Array.isArray(cond)) { const ops = Object.keys(cond as object); if (ops.length !== 1 || ops[0] !== '$in') { throw new Error(`fake engine: unsupported filter operator(s) ${ops.join(',')} on '${key}'`); } - const set = (cond as { $in: unknown[] }).$in.map(String); + const set = inMembers((cond as { $in: unknown }).$in, tables.sys_record_share).map(String); return set.includes(String(row[key])); } return String(row[key]) === String(cond); @@ -347,7 +354,9 @@ describe('[#7858] ownership scoping vs federated (external) objects', () => { userId: MEMBER, __readScope: 'own', } as never); - expect(read).toEqual({ owner_id: MEMBER }); + // A fake engine cannot say where the object is stored, so the share arm + // is written (ADR-0155 R2 reads the engine's answer; none is no R2). + expect(read).toEqual({ $or: [{ owner_id: MEMBER }, { id: { $in: SharedRecordIds.read('ext_with_real_owner', MEMBER) } }] }); const write = await svc.buildWriteFilter( 'ext_with_real_owner', @@ -362,7 +371,7 @@ describe('[#7858] ownership scoping vs federated (external) objects', () => { userId: MEMBER, __readScope: 'own', } as never); - expect(read).toEqual({ owner_id: MEMBER }); + expect(read).toEqual({ $or: [{ owner_id: MEMBER }, { id: { $in: SharedRecordIds.read('local_task', MEMBER) } }] }); const write = await svc.buildWriteFilter( 'local_task', diff --git a/packages/plugins/plugin-sharing/src/field-recipient.test.ts b/packages/plugins/plugin-sharing/src/field-recipient.test.ts index 76822f018fc..408c06db3f3 100644 --- a/packages/plugins/plugin-sharing/src/field-recipient.test.ts +++ b/packages/plugins/plugin-sharing/src/field-recipient.test.ts @@ -52,6 +52,7 @@ import { bindRuleHooks, unbindAllRuleHooks, SHARING_RULE_HOOK_PACKAGE } from './ import { bindBusinessUnitTreeRecompute } from './bu-tree-recompute.js'; import { createDeclaredSharingRuleSource } from './declared-sharing-rules.js'; import { SysSharingRule } from './objects/sys-sharing-rule.object.js'; +import { inMembers } from './shared-record-ids.testkit.js'; interface Row { [k: string]: any } @@ -61,19 +62,20 @@ const ADMIN_SESSION = { isSystem: false, userId: 'admin' }; type HookEntry = { event: string; handler: (ctx: any) => any; options: Row }; -function matches(row: Row, f: any): boolean { +function matches(row: Row, f: any, shares?: Row[]): boolean { if (!f || typeof f !== 'object') return true; // A combinator is CONJOINED with its sibling field keys, never a // short-circuit that returns before they are read (#7676) — `listRules` // composes `{object_name, active, $or:[…org scope…]}`. - if (Array.isArray(f.$or) && !f.$or.some((x: any) => matches(row, x))) return false; - if (Array.isArray(f.$and) && !f.$and.every((x: any) => matches(row, x))) return false; + if (Array.isArray(f.$or) && !f.$or.some((x: any) => matches(row, x, shares))) return false; + if (Array.isArray(f.$and) && !f.$and.every((x: any) => matches(row, x, shares))) return false; for (const [k, v] of Object.entries(f)) { if (k === '$or' || k === '$and') continue; const rv = row[k]; if (v != null && typeof v === 'object' && !Array.isArray(v)) { const op: any = v; - if ('$in' in op) { if (!op.$in.includes(rv)) return false; continue; } + // [ADR-0155] A share-grant leaf resolves over the double's own share rows. + if ('$in' in op) { if (!inMembers(op.$in, shares).includes(rv)) return false; continue; } if ('$ne' in op) { if (rv === op.$ne) return false; continue; } if ('$gte' in op) { if (!(rv >= op.$gte)) return false; continue; } } @@ -112,7 +114,7 @@ function makeEngine() { throw err; } const f = opts?.filter ?? opts?.where; - return ensure(o).filter((r) => matches(r, f)).slice(0, opts?.limit ?? 10000); + return ensure(o).filter((r) => matches(r, f, tables.sys_record_share)).slice(0, opts?.limit ?? 10000); }, /** * [#14754] A recipient whose `sys_record_share` INSERT the engine refuses, @@ -136,7 +138,7 @@ function makeEngine() { const t = ensure(o); const targets = verdict.kind === 'by-id' ? t.filter((r) => r.id === verdict.id) - : t.filter((r) => matches(r, options?.where)); + : t.filter((r) => matches(r, options?.where, tables.sys_record_share)); for (const r of targets) Object.assign(r, data); return verdict.kind === 'by-id' ? (targets[0] ?? null) : targets.length; }, @@ -974,10 +976,15 @@ describe('two rules reaching one user on one record keep one grant each — the .filter((r) => r.record_id === recordId && r.recipient_id === 'u_p') .map((r) => `${r.source_id}:${r.access_level}`) .sort(); - /** Does P's read scope reach `recordId`? Through the same filter every `find` is AND-ed with. */ + /** + * Does P's read scope reach `recordId`? Through the same filter every `find` + * is AND-ed with, applied by the double to the stored record: the share arm + * is the leaf (ADR-0155), which carries no id to search the filter for. + */ const readsRecord = async (recordId = 'prj_1') => { const filter: any = await h.sharing.buildReadFilter(OBJECT, P); - return JSON.stringify(filter).includes(`"${recordId}"`); + const rows = await h.engine.find(OBJECT, { where: { $and: [{ id: recordId }, filter ?? {}] } }); + return rows.length === 1; }; beforeEach(() => { diff --git a/packages/plugins/plugin-sharing/src/objects/sys-record-share.object.ts b/packages/plugins/plugin-sharing/src/objects/sys-record-share.object.ts index 307ab44a27e..a4372ffd6d7 100644 --- a/packages/plugins/plugin-sharing/src/objects/sys-record-share.object.ts +++ b/packages/plugins/plugin-sharing/src/objects/sys-record-share.object.ts @@ -12,8 +12,10 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; * * Enforcement lives in `@objectstack/plugin-sharing`: * - For objects with `sharingModel: 'private'`, the engine middleware - * AND-s `{$or:[{owner_id:userId},{id:{$in:[grantedRecordIds]}}]}` - * into every `find` against that object. + * AND-s `{$or:[{owner_id:userId},{id:{$in:SharedRecordIds.read(object,userId)}}]}` + * into every `find` against that object: the share-grant leaf + * (ADR-0155), which the driver evaluates as a semi-join on this table, + * so every grant counts and none is read into memory. * - For objects with `sharingModel: 'private' | 'read'`, the same * middleware enforces edit/delete by checking ownership OR a share * row with `access_level in ('edit','full')`. `full` is no longer @@ -314,8 +316,8 @@ export const SysRecordShare = ObjectSchema.create({ indexes: [ // Hot path: "all records visible to user U on object O" — the - // middleware reads (object_name, recipient_type, recipient_id) to - // build the `id IN (...)` predicate on every find. + // share-grant leaf's semi-join (ADR-0155) reads (object_name, + // recipient_type, recipient_id) inside every sharing-scoped statement. { fields: ['object_name', 'recipient_type', 'recipient_id'] }, // "all grants on this record" — used by the share-management UI // and by canEdit() to look up explicit grants. diff --git a/packages/plugins/plugin-sharing/src/share-arm-boot.test.ts b/packages/plugins/plugin-sharing/src/share-arm-boot.test.ts new file mode 100644 index 00000000000..3b982266c8b --- /dev/null +++ b/packages/plugins/plugin-sharing/src/share-arm-boot.test.ts @@ -0,0 +1,291 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 ② ruled, plan step 6] The two tightenings that land with the + * switch, each where it takes effect. + * + * - **R2, the storage rows.** On an object whose storage cannot evaluate the + * share-grant leaf (another datasource than `sys_record_share`, or a driver + * that does not declare `SharedRecordIds`), share grants stop counting: no + * scope carries the share arm, the write gate consults no grant, the grant + * door and the sharing-rule save door refuse with `SHARING_NOT_ENABLED`, and + * the boot names every such object that holds share rows. + * - **R1 at boot, the host class.** A middleware or a find hook registered + * for `sys_record_share` BY NAME refuses the boot with D4's envelope, + * `INTERNAL_ERROR` / 500; one registered with no object, or `'*'`, does not. + * A registration made after boot meets the engine seam's refusal at read. + * + * Real `ObjectQL`, a real `SqlDriver` holding `sys_record_share`, and, for the + * other datasource, a recording driver that declares no fixed-read leaf. The + * recognition of both classes is the engine's own (`fixedReadLeafClassOf`). + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { ObjectKernel, type PluginContext } from '@objectstack/core'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ERROR_CODE_LEDGER } from '@objectstack/spec/api'; +import { isFixedReadLeaf } from '@objectstack/spec/data'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; + +import { SharingService } from './sharing-service.js'; +import { SharingServicePlugin, buildSharingMiddleware } from './sharing-plugin.js'; +import { bindRuleObjectEnforcementGuard } from './rule-hooks.js'; +import { SysRecordShare } from './objects/sys-record-share.object.js'; +import { registeredObjectNames, reportInertShareGrantHolders, shareGrantRegistrationRefusal } from './share-arm-boot.js'; + +const ORG = 'org_r2'; +const ME = 'u_me'; +const OTHER = 'u_other'; +/** On the datasource of `sys_record_share`, a SQL driver: share grants count. */ +const LOCAL = 'r2_local'; +/** On another datasource: share grants stop counting, and it holds share rows. */ +const FAR = 'r2_far'; +/** On another datasource too, holding no share row: not named by the report. */ +const FAR_EMPTY = 'r2_far_empty'; + +const SYSTEM = { isSystem: true, positions: [], permissions: [] } as unknown as ExecutionContext; +const ADMIN = { + userId: 'u_admin', organizationId: ORG, tenantId: ORG, positions: [], permissions: [], systemPermissions: ['manage_sharing'], +} as unknown as ExecutionContext; +const asMe = () => ({ userId: ME }) as unknown as ExecutionContext; + +const text = (name: string) => ({ type: 'text', name, label: name }); +const RULE_FIELDS = Object.fromEntries( + ['organization_id', 'name', 'label', 'object_name', 'criteria_json', 'recipient_type', 'recipient_id', 'access_level', 'managed_by'] + .map((f) => [f, text(f)]), +); + +type Envelope = { code?: string; status?: number; message?: string }; +const refusalOf = (p: Promise): Promise => p.then(() => null, (e: Envelope) => e); + +/** Every fixed-read leaf in `node`, by identity. */ +function leavesIn(node: unknown, out: unknown[] = []): unknown[] { + if (isFixedReadLeaf(node)) out.push(node); + else if (node !== null && typeof node === 'object') for (const v of Object.values(node)) leavesIn(v, out); + return out; +} + +/** A driver on datasource `legacy` that declares no fixed-read leaf, and records what it is handed. */ +function legacyDriver() { + const seen: Array<{ verb: string; ast: any }> = []; + const rows = [ + { id: 'f_mine', name: 'mine', owner_id: ME, organization_id: ORG }, + { id: 'f_shared', name: 'shared to me', owner_id: OTHER, organization_id: ORG }, + ]; + const byId = (ast: any) => (typeof ast?.where?.id === 'string' ? rows.filter((r) => r.id === ast.where.id) : rows); + const driver: any = { + name: 'legacy', version: '0.0.0', supports: {}, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async find(_object: string, ast: any) { seen.push({ verb: 'find', ast }); return byId(ast); }, + async findOne(_object: string, ast: any) { seen.push({ verb: 'findOne', ast }); return byId(ast)[0] ?? null; }, + async count(_object: string, ast: any) { seen.push({ verb: 'count', ast }); return byId(ast).length; }, + async create(_object: string, data: Record) { return data; }, + async update(_object: string, _id: string, data: Record) { return data; }, + async delete() { return true; }, + }; + return { driver, seen }; +} + +const open: SqlDriver[] = []; +afterEach(async () => { + while (open.length) await open.pop()!.disconnect().catch(() => undefined); +}); + +async function boot() { + const sql = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + open.push(sql); + const legacy = legacyDriver(); + const ql = new ObjectQL(); + ql.registerDriver(sql as never, true); + ql.registerDriver(legacy.driver); + await ql.init(); + ql.setTenancyPostureProvider(() => 'single'); + ql.registerObject({ name: LOCAL, label: 'Local', sharingModel: 'private', fields: { name: text('name') } } as never); + ql.registerObject({ name: FAR, label: 'Far', sharingModel: 'private', datasource: 'legacy', fields: { name: text('name') } } as never); + ql.registerObject({ name: FAR_EMPTY, label: 'Far, empty', sharingModel: 'private', datasource: 'legacy', fields: { name: text('name') } } as never); + ql.registerObject(SysRecordShare as never); + ql.registerObject({ + name: 'sys_sharing_rule', label: 'Sharing Rule', isSystem: true, + fields: { id: { ...text('id'), primary: true }, ...RULE_FIELDS, active: { type: 'boolean', name: 'active', label: 'Active' } }, + } as never); + await sql.initObjects([LOCAL, 'sys_record_share', 'sys_sharing_rule'].map((name) => ql.getSchema(name) as never)); + const knex = (sql as unknown as { knex: any }).knex; + await knex(LOCAL).insert([ + { id: 'l_mine', name: 'mine', owner_id: ME, organization_id: ORG }, + { id: 'l_shared', name: 'shared to me', owner_id: OTHER, organization_id: ORG }, + ]); + // An edit grant to the caller on one row of each object. + await knex('sys_record_share').insert([LOCAL, FAR].map((object, i) => ({ + id: `g_${i}`, object_name: object, record_id: object === LOCAL ? 'l_shared' : 'f_shared', + recipient_type: 'user', recipient_id: ME, access_level: 'edit', source: 'manual', organization_id: ORG, + }))); + const warn = vi.fn(); + const sharing = new SharingService({ engine: ql as never, logger: { warn, error: vi.fn(), info: vi.fn() } as never }); + ql.registerMiddleware(buildSharingMiddleware(sharing) as never, { object: '*' }); + bindRuleObjectEnforcementGuard(ql as never, sharing); + return { ql, sql, knex, legacy, sharing, warn }; +} + +describe('[ADR-0155 ② ruled R2] the storage rows: share grants stop counting where no driver evaluates them', () => { + let h: Awaited>; + beforeEach(async () => { h = await boot(); }); + + it('the reason names the two datasources; an object beside sys_record_share on a SQL driver has none', () => { + expect(h.sharing.shareGrantsInertReason(FAR)).toMatch(/'r2_far' is bound to datasource 'legacy' while 'sys_record_share' is bound to/); + expect(h.sharing.shareGrantsInertReason(LOCAL)).toBeNull(); + }); + + it('neither scope carries the share arm there, and the read reaches the driver with no leaf; the control keeps it', async () => { + expect(leavesIn(await h.sharing.buildReadFilter(FAR, asMe()))).toHaveLength(0); + expect(await h.sharing.buildWriteFilter(FAR, asMe())).toEqual({ owner_id: ME }); + expect(leavesIn(await h.sharing.buildReadFilter(LOCAL, asMe()))).toHaveLength(1); + expect(leavesIn(await h.sharing.buildWriteFilter(LOCAL, asMe()))).toHaveLength(1); + await h.ql.find(FAR, {}, { context: asMe() } as never); + const read = h.legacy.seen.find((c) => c.verb === 'find'); + expect(read).toBeDefined(); + expect(leavesIn(read!.ast)).toHaveLength(0); + expect(JSON.stringify(read!.ast.where)).toContain(ME); + }); + + it('the write gate consults no grant there: the edit grant on f_shared does not admit an edit, as l_shared\'s does', async () => { + expect(await h.sharing.checkEdit(FAR, 'f_shared', asMe())).toBe('deny'); + expect(await h.sharing.checkEdit(FAR, 'f_mine', asMe())).toBe('allow'); + expect(await h.sharing.checkEdit(LOCAL, 'l_shared', asMe())).toBe('allow'); + }); + + it('the grant door refuses, system and direct callers alike, with SHARING_NOT_ENABLED and the reason', async () => { + for (const context of [SYSTEM, ADMIN]) { + const err = await refusalOf(h.sharing.grant({ object: FAR, recordId: 'f_mine', recipientId: OTHER, accessLevel: 'read' } as never, context)); + // The code is the message prefix the REST share routes map to 422 (`sharing-routes.ts`). + expect(err?.message).toMatch(/^SHARING_NOT_ENABLED: 'r2_far' is bound to datasource 'legacy'/); + } + expect(ERROR_CODE_LEDGER['@objectstack/plugin-sharing']).toContain('SHARING_NOT_ENABLED'); + }); + + it('the sharing-rule save door refuses with SHARING_NOT_ENABLED / 422 and says how to share the object again', async () => { + const row = { + id: 'sr_far', organization_id: ORG, name: 'far_rule', label: 'far_rule', object_name: FAR, criteria_json: '{}', + recipient_type: 'position', recipient_id: 'sales_rep', access_level: 'read', active: true, managed_by: 'admin', + }; + const err = await refusalOf(h.ql.insert('sys_sharing_rule', row, { context: ADMIN } as never)); + expect(err?.code).toBe('SHARING_NOT_ENABLED'); + expect(err?.status).toBe(422); + expect(err?.message).toContain(`store '${FAR}' on the datasource of 'sys_record_share'`); + }); + + it('the boot names, once at warn, every such object that holds share rows, and only those', async () => { + const log = { warn: vi.fn() }; + const named = await reportInertShareGrantHolders(h.sharing, registeredObjectNames(h.ql), log); + expect(named.map((n) => n.object)).toEqual([FAR]); + expect(log.warn).toHaveBeenCalledTimes(1); + const [message, meta] = log.warn.mock.calls[0] as [string, { objects: Array<{ object: string }> }]; + expect(message).toContain(`'${FAR}'`); + expect(message).not.toContain(`'${FAR_EMPTY}'`); + expect(message).toContain('SHARING_NOT_ENABLED'); + expect(meta.objects.map((o) => o.object)).toEqual([FAR]); + }); + + it('the boot report is silent when no such object holds a share row', async () => { + await h.knex('sys_record_share').where({ object_name: FAR }).del(); + const log = { warn: vi.fn() }; + expect(await reportInertShareGrantHolders(h.sharing, registeredObjectNames(h.ql), log)).toEqual([]); + expect(log.warn).not.toHaveBeenCalled(); + }); +}); + +describe('[ADR-0155 ② ruled R2] a driver beside sys_record_share that does not declare the leaf', () => { + const engineWith = (members: Record) => new SharingService({ + engine: { getSchema: () => ({ name: 'doc', sharingModel: 'private', fields: { owner_id: { type: 'lookup' } } }), find: async () => [], ...members } as never, + }); + + it('is named by its driver', () => { + const sharing = engineWith({ getDriverForObject: () => ({ name: 'mongo-like', supports: {} }), fixedReadLeafClassOf: () => null }); + expect(sharing.shareGrantsInertReason('doc')).toMatch(/stored by driver 'mongo-like', which does not evaluate a share grant/); + }); + + it('an engine that cannot say writes the leaf, and the seam stands behind it', () => { + expect(engineWith({}).shareGrantsInertReason('doc')).toBeNull(); + expect(engineWith({ getDriverForObject: () => { throw new Error('boom'); } }).shareGrantsInertReason('doc')).toBeNull(); + const declaring = { getDriverForObject: () => ({ name: 'sql', supports: { fixedReadLeaves: ['SharedRecordIds'] } }) }; + expect(engineWith({ ...declaring, fixedReadLeafClassOf: () => { throw new Error('boom'); } }).shareGrantsInertReason('doc')).toBeNull(); + }); +}); + +describe('[ADR-0155 ② ruled R1 at boot] a registration for sys_record_share by name refuses the boot', () => { + let h: Awaited>; + beforeEach(async () => { h = await boot(); }); + const REFUSED = { code: 'INTERNAL_ERROR', status: 500 }; + const envelope = (e: Envelope | undefined) => ({ code: e?.code, status: e?.status }); + + it('a clean host is not refused', () => { + expect(shareGrantRegistrationRefusal(h.ql as never)).toBeUndefined(); + }); + + it('an object-scoped middleware for it', () => { + h.ql.registerMiddleware((async (_ctx: unknown, next: () => Promise) => next()) as never, { object: 'sys_record_share' }); + const refusal = shareGrantRegistrationRefusal(h.ql as never); + expect(envelope(refusal)).toEqual(REFUSED); + expect(refusal?.message).toContain("an object-scoped middleware registered for 'sys_record_share'"); + }); + + for (const event of ['beforeFind', 'afterFind']) { + it(`a ${event} hook naming it, with no exemption for one that skips system reads`, () => { + h.ql.registerHook(event, (async (ctx: any) => { if (ctx?.session?.isSystem) return; }) as never, { object: 'sys_record_share' }); + const refusal = shareGrantRegistrationRefusal(h.ql as never); + expect(envelope(refusal)).toEqual(REFUSED); + expect(refusal?.message).toContain(`a ${event} hook registered for 'sys_record_share' by name`); + }); + } + + it("a registration that names no object, or '*', is outside the class", () => { + h.ql.registerMiddleware((async (_ctx: unknown, next: () => Promise) => next()) as never, { object: '*' }); + h.ql.registerHook('beforeFind', (async () => {}) as never); + h.ql.registerHook('afterFind', (async () => {}) as never, { object: '*' }); + expect(shareGrantRegistrationRefusal(h.ql as never)).toBeUndefined(); + }); + + it('an engine without the recognition, or whose recognition throws, logs once at warn and does not refuse', () => { + const log = { warn: vi.fn() }; + expect(shareGrantRegistrationRefusal({}, log)).toBeUndefined(); + expect(shareGrantRegistrationRefusal({ fixedReadLeafClassOf: () => { throw new Error('boom'); } }, log)).toBeUndefined(); + expect(log.warn).toHaveBeenCalledTimes(2); + expect(String(log.warn.mock.calls[0][0])).toContain('did not run'); + }); + + it('a registration made after boot meets the engine seam\'s refusal at read', async () => { + h.ql.registerMiddleware((async (_ctx: unknown, next: () => Promise) => next()) as never, { object: 'sys_record_share' }); + const err = await refusalOf(h.ql.find(LOCAL, {}, { context: asMe() } as never)); + expect(envelope(err ?? undefined)).toEqual(REFUSED); + }); +}); + +describe('[ADR-0155 ② ruled R1 at boot] the plugin refuses the boot at kernel:bootstrapped', () => { + /** Start the plugin over `ql` and run its boot hooks in order, as the kernel does; the first throw is the boot's. */ + async function bootPlugin(ql: ObjectQL): Promise { + const kernel = new ObjectKernel({ skipSystemValidation: true, gracefulShutdown: false } as never); + const hooks: Record Promise | void>> = {}; + const ctx = { + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, + hook: (event: string, handler: () => Promise | void) => { (hooks[event] ??= []).push(handler); }, + getService: (name: string): T => (name === 'objectql' ? (ql as unknown as T) : kernel.getService(name)), + registerService: vi.fn(), + getKernel: () => kernel, + }; + const plugin = new SharingServicePlugin({ enforce: false }); + await plugin.start(ctx as unknown as PluginContext); + return refusalOf((async () => { + for (const event of ['kernel:ready', 'kernel:bootstrapped']) for (const handler of hooks[event] ?? []) await handler(); + })()); + } + + it('a host with a find hook for sys_record_share by name does not finish booting; a clean host does', async () => { + const clean = await boot(); + expect(await bootPlugin(clean.ql)).toBeNull(); + const host = await boot(); + host.ql.registerHook('afterFind', (async () => {}) as never, { object: 'sys_record_share' }); + const err = await bootPlugin(host.ql); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INTERNAL_ERROR', status: 500 }); + expect(err?.message).toContain("afterFind hook registered for 'sys_record_share' by name"); + }); +}); diff --git a/packages/plugins/plugin-sharing/src/share-arm-boot.ts b/packages/plugins/plugin-sharing/src/share-arm-boot.ts new file mode 100644 index 00000000000..688421844d0 --- /dev/null +++ b/packages/plugins/plugin-sharing/src/share-arm-boot.ts @@ -0,0 +1,145 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 plan step 6] The two boot-time answers that land with the switch, + * the moment the sharing service starts writing the share-grant leaf + * (`SharedRecordIds`) into every sharing-scoped read. + * + * - **R1 at boot, the host class (② ruled).** A host that registers an + * object-scoped middleware, or a `beforeFind` / `afterFind` hook, for + * `sys_record_share` BY NAME is in D4's second class: today's grant read + * ran that registration, and the leaf's subquery would read around it. The + * engine seam never reads around it, so every sharing-scoped read on such a + * host would fail with 500; the boot is refused instead, naming the + * registration, before any request is served. The class is kept whole: + * there is no exemption for a registration that skips system reads. A + * registration that names no object, or `'*'`, is outside the class (D4's + * boundary): nothing here refuses, reports or logs it, and the changeset + * tells the host. A registration made after boot meets the seam's refusal + * at read. The recognition is the engine's own + * (`IObjectQLEngine.fixedReadLeafClassOf`), ⛔ never restated here. + * - **R2's report, the storage rows (② ruled).** On an object whose storage + * cannot evaluate the leaf (`SharingService.shareGrantsInertReason`), share + * grants stop counting at the switch. ADR-0111 D10 asks that tightening to + * fail closed with a visible trail: the boot names, at `warn`, every such + * object that holds `sys_record_share` rows, with the reason. It never + * fails the boot. + */ + +import { SharedRecordIds } from '@objectstack/spec/data'; +import type { EngineFixedReadLeafClass } from '@objectstack/spec/contracts'; +import { fixedReadLeafRefusal, type FixedReadLeafRefusalError } from '@objectstack/core'; +import type { SharingService } from './sharing-service.js'; + +/** The table the share-grant leaf reads; the host class is recognised for it. */ +const SHARE_TABLE = 'sys_record_share'; + +/** + * The recipient of the leaf the boot check builds only to ask the engine's + * recognition: it reads the leaf's object and table, never its recipient, and + * the leaf is handed to no evaluator. + */ +const BOOT_CHECK_PROBE_RECIPIENT = 'share-arm-boot-probe'; + +/** What the boot check reads off the engine. */ +export interface ShareArmBootEngine { + fixedReadLeafClassOf?(leaf: SharedRecordIds): EngineFixedReadLeafClass | null; +} + +/** The boot log both answers write to. */ +export interface ShareArmBootLog { + warn?: (message: string, meta?: Record) => void; +} + +/** + * [ADR-0155 ② ruled R1 at boot] The refusal a host in D4's second class gets + * at boot, or `undefined` when it is not in it. + * + * Asked with a leaf whose object IS the share table, so the first class + * (another datasource) can never answer in place of the second. An engine + * without the recognition, or one whose recognition throws, cannot say: that + * is logged once at `warn` and the boot goes on, with the seam's own refusal + * at read behind it. + * + * The refusal is D4's envelope, `INTERNAL_ERROR` / 500 (`@objectstack/core`'s + * `fixedReadLeafRefusal`): the fault is the host's composition, never a + * request's. + */ +export function shareGrantRegistrationRefusal( + engine: ShareArmBootEngine | undefined, + log?: ShareArmBootLog, +): FixedReadLeafRefusalError | undefined { + if (!engine || typeof engine.fixedReadLeafClassOf !== 'function') { + log?.warn?.( + 'SharingServicePlugin: the engine cannot say whether this host registers a middleware or a find hook for ' + + `'${SHARE_TABLE}' by name (it has no fixedReadLeafClassOf), so the boot check for that registration did ` + + 'not run; such a registration is refused at read by the engine seam instead (ADR-0155 D4)', + ); + return undefined; + } + let recognised: EngineFixedReadLeafClass | null; + try { + recognised = engine.fixedReadLeafClassOf(SharedRecordIds.read(SHARE_TABLE, BOOT_CHECK_PROBE_RECIPIENT)); + } catch (err) { + log?.warn?.( + `SharingServicePlugin: the engine's recognition of a registration for '${SHARE_TABLE}' by name failed, so ` + + 'the boot check for it did not run; such a registration is refused at read by the engine seam instead ' + + '(ADR-0155 D4)', + { error: err instanceof Error ? err.message : String(err) }, + ); + return undefined; + } + if (recognised?.class !== 'registration-by-name') return undefined; + return fixedReadLeafRefusal( + 'plugin-sharing', + `the host carries ${recognised.registration}, which a read of '${recognised.table}' runs and the share-grant ` + + 'subquery every sharing-scoped read now carries would read around (ADR-0155 D4). The engine never reads ' + + 'around it, so every such read would fail; the boot is refused before any request is served. Remove that ' + + `registration for '${recognised.table}'. A host that opted '${recognised.table}' into record-view auditing ` + + 'gives up that auditing of share rows by removing it. A registration that names no object, or \'*\', is not ' + + 'refused.', + ); +} + +/** One object whose share grants stopped counting and that holds share rows. */ +export interface InertShareGrantHolder { + readonly object: string; + readonly reason: string; +} + +/** + * [ADR-0155 ② ruled R2] Name, at `warn`, every object whose share grants + * stopped counting at the switch and that holds `sys_record_share` rows. + * Returns what it named. Silent when there is none, which on a host whose + * objects all live with `sys_record_share` on a SQL driver costs no read. + */ +export async function reportInertShareGrantHolders( + sharing: Pick, + objects: readonly string[], + log?: ShareArmBootLog, +): Promise { + const holders = await sharing.inertShareGrantHolders(objects); + if (holders.length === 0) return holders; + log?.warn?.( + `SharingServicePlugin: share grants no longer count on ${holders.length} object(s) that hold ` + + `'${SHARE_TABLE}' rows, because their storage does not evaluate the share-grant subquery (ADR-0155 R2): ` + + `${holders.map((h) => `'${h.object}'`).join(', ')}. Owner, queue and approval access on them is unchanged; ` + + 'those rows are not consulted, and a new grant or sharing rule on them is refused (SHARING_NOT_ENABLED). To ' + + `share their records again, store them on the datasource of '${SHARE_TABLE}', on a driver that evaluates ` + + 'share grants (the SQL drivers do).', + { objects: holders.map((h) => ({ object: h.object, reason: h.reason })) }, + ); + return holders; +} + +/** The names of every object the engine's registry holds, or `[]` when it has no registry. */ +export function registeredObjectNames(engine: unknown): string[] { + const registry = (engine as { registry?: { getAllObjects?: () => unknown[] } } | undefined)?.registry; + if (!registry || typeof registry.getAllObjects !== 'function') return []; + const names = new Set(); + for (const schema of registry.getAllObjects() ?? []) { + const name = (schema as { name?: unknown } | null)?.name; + if (typeof name === 'string' && name !== '') names.add(name); + } + return [...names].sort(); +} diff --git a/packages/plugins/plugin-sharing/src/shared-record-ids-switch.test.ts b/packages/plugins/plugin-sharing/src/shared-record-ids-switch.test.ts new file mode 100644 index 00000000000..4f9724c995f --- /dev/null +++ b/packages/plugins/plugin-sharing/src/shared-record-ids-switch.test.ts @@ -0,0 +1,315 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 D6, plan step 6] The switch, end to end: the sharing scopes carry + * the share-grant leaf (`SharedRecordIds`) where they used to carry an id list + * read with `limit: 5000`. + * + * Real `ObjectQL`, real `SqlDriver`, the real sharing middleware and the real + * `sys_record_share` object (its indexes included). One private object holds + * 1,000 rows the caller owns, 6,000 rows another user owns, one row sitting + * in a queue the caller belongs to, one row a pending approval step waits on + * the caller for, and rows nothing admits. The caller's grants grow from + * 5,000 to 5,001 to 6,000 across the cases, so the cases run in order. + * + * "Today's list" is the retired statement, rebuilt here from what it read: the + * grant rows under `limit: 5000` (plus the approval ids, which it merged into + * the same list), OR-ed beside the owner and queue arms and run as a system + * read. It is the control each pin compares against, not a second scope. + * + * ## The dialect axis + * + * The SQLite cell always runs. The PostgreSQL cell runs where + * `OS_TEST_POSTGRES_URL` is set and is a named skip otherwise; it owns one + * schema, created before and dropped after. No CI job provisions that variable + * for this package, so the PostgreSQL cell is red-capable and un-run in CI; + * the change that landed this file carries its local PostgreSQL run. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectQL, ObjectQLPlugin, driverEvaluatesFixedReadLeaf } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ReadableIds, resolveInjectedColumnProvenance } from '@objectstack/spec/data'; + +import { SharingService } from './sharing-service.js'; +import { buildSharingMiddleware } from './sharing-plugin.js'; +import { SysRecordShare } from './objects/sys-record-share.object.js'; +import { WRITE_ACCESS_LEVELS } from './access-level.js'; + +const DEAL = 'd6_deal'; +const LINE = 'd6_line'; +const ME = 'u_me'; +const OTHER = 'u_other'; +const AGENT = 'u_agent'; +const QUEUE = 'q_sales'; +const ORG = 'org_d6'; + +const OWNED = 1000; +const pad = (n: number) => String(n).padStart(4, '0'); +const ownId = (i: number) => `own_${pad(i)}`; +const shrId = (i: number) => `shr_${pad(i)}`; +/** Sits in the caller's queue, owner empty. */ +const QUEUED = 'q_0001'; +/** Sits in a queue the caller is not in. */ +const QUEUED_ELSEWHERE = 'q_0002'; +/** A pending approval step waits on the caller for it. */ +const APPROVAL = 'apr_0001'; +/** Nothing admits it: another owner, and only noise grants name it. */ +const NEVER = 'x_0001'; + +/** Every thousandth grant is read-only; the rest are `edit`, so both scopes pass the cap. */ +const accessOf = (i: number) => (i % 1000 === 0 ? 'read' : 'edit'); +const editGrantsUpTo = (n: number) => n - Math.floor(n / 1000); + +const SYSTEM = { isSystem: true }; +const asMe = () => ({ userId: ME }); +const asAgentForMe = () => ({ userId: AGENT, onBehalfOf: { userId: ME } }); + +const DEAL_DEF = { name: DEAL, label: 'D6 deal', sharingModel: 'private', fields: { name: { type: 'text', label: 'Name' } } }; +const LINE_DEF = { + name: LINE, + label: 'D6 line', + sharingModel: 'public_read_write', + fields: { name: { type: 'text', label: 'Name' }, deal_id: { type: 'text', label: 'Deal' } }, +}; + +interface Cell { id: string; config: () => Record | null } + +const PG_SCHEMA = `d6_switch_${process.pid}_${Date.now().toString(36)}`; +const CELLS: Cell[] = [ + { id: 'sqlite', config: () => ({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) }, + { + id: 'postgres', + config: () => (process.env.OS_TEST_POSTGRES_URL + ? { client: 'pg', connection: process.env.OS_TEST_POSTGRES_URL, searchPath: [PG_SCHEMA] } + : null), + }, +]; + +for (const cell of CELLS) { + const config = cell.config(); + describe.skipIf(config === null)(`[ADR-0155 D6] the share-grant leaf in the sharing scopes · ${cell.id}`, () => { + let driver: SqlDriver; + let ql: ObjectQL; + let knex: any; + /** The queue and approval arms are wired while this is on. */ + let arms = true; + let grantsSeeded = 0; + let marker = 0; + + const sharing = () => new SharingService({ + engine: ql as never, + ownershipQueues: () => (arms + ? { queuesOf: async () => [QUEUE], isMember: async (_u: string, q: string) => q === QUEUE } + : null) as never, + approvals: () => (arms + ? { pendingApproverReadGrants: async (object: string) => new Map(object === DEAL ? [[APPROVAL, ['req_1']]] : []) } + : null), + }); + + const shareRow = (id: string, record: string, recipient: string, access: string, extra: Record = {}) => ({ + id, object_name: DEAL, record_id: record, recipient_type: 'user', recipient_id: recipient, access_level: access, + source: 'manual', organization_id: ORG, ...extra, + }); + + /** The caller's grants on `shr_0001` … `shr_`. */ + async function growGrantsTo(n: number): Promise { + const rows = []; + for (let i = grantsSeeded + 1; i <= n; i++) rows.push(shareRow(`g_me_${pad(i)}`, shrId(i), ME, accessOf(i))); + if (rows.length > 0) await knex.batchInsert('sys_record_share', rows, 200); + grantsSeeded = n; + const [{ n: stored }] = await knex('sys_record_share').where({ recipient_id: ME, object_name: DEAL, recipient_type: 'user' }).count({ n: '*' }); + expect(Number(stored), 'the grants the caller holds on the object').toBe(n); + } + + /** The retired statement's scope: the grant rows under `limit: 5000`, merged with the approval ids. */ + async function todaysScope(verb: 'read' | 'update'): Promise> { + const grants = await ql.find('sys_record_share', { + where: { + object_name: DEAL, recipient_type: 'user', recipient_id: ME, + ...(verb === 'update' ? { access_level: { $in: [...WRITE_ACCESS_LEVELS] } } : {}), + }, + fields: ['record_id'], + limit: 5000, + }, { context: SYSTEM } as never); + const listed = new Set( + (grants as Array<{ record_id: unknown }>) + .map((g) => g.record_id).filter((v) => v != null).map(String).filter((v) => v !== ''), + ); + if (verb === 'read' && arms) listed.add(APPROVAL); + const disjuncts: unknown[] = [{ owner_id: ME }]; + if (arms) disjuncts.push({ owner_id: null, queue: QUEUE }); + if (listed.size > 0) disjuncts.push({ id: { $in: [...listed] } }); + return disjuncts.length === 1 ? (disjuncts[0] as Record) : { $or: disjuncts }; + } + + const ids = (rows: unknown) => (rows as Array<{ id: string }>).map((r) => String(r.id)).sort(); + const leafIds = async (context: Record) => ids(await ql.find(DEAL, { fields: ['id'] }, { context } as never)); + const listIds = async () => ids(await ql.find(DEAL, { where: await todaysScope('read'), fields: ['id'] }, { context: SYSTEM } as never)); + const leafCount = (context: Record) => ql.count(DEAL, {}, { context } as never); + const listCount = async () => ql.count(DEAL, { where: await todaysScope('read') }, { context: SYSTEM } as never); + const leafGet = async (id: string, context: Record = asMe()) => + (await ql.findOne(DEAL, { where: { id } }, { context } as never)) !== null; + const listGet = async (id: string) => + (await ql.findOne(DEAL, { where: { $and: [{ id }, await todaysScope('read')] } }, { context: SYSTEM } as never)) !== null; + + /** A predicate `update` the caller makes, and the ids it touched. */ + async function leafUpdate(context: Record): Promise { + const name = `touched_${++marker}`; + await ql.update(DEAL, { name }, { where: { name: { $ne: '__never__' } }, multi: true, context } as never); + return ids(await ql.find(DEAL, { where: { name }, fields: ['id'] }, { context: SYSTEM } as never)); + } + async function listUpdate(): Promise { + const name = `touched_${++marker}`; + const where = { $and: [{ name: { $ne: '__never__' } }, await todaysScope('update')] }; + await ql.update(DEAL, { name }, { where, multi: true, context: SYSTEM } as never); + return ids(await ql.find(DEAL, { where: { name }, fields: ['id'] }, { context: SYSTEM } as never)); + } + + beforeAll(async () => { + driver = new SqlDriver(config as never); + knex = (driver as unknown as { knex: any }).knex; + if (cell.id === 'postgres') await knex.raw('CREATE SCHEMA IF NOT EXISTS ??', [PG_SCHEMA]); + ql = new ObjectQL(); + ql.registerDriver(driver as never, true); + await ql.init(); + ql.registerObject(DEAL_DEF as never); + ql.registerObject(LINE_DEF as never); + ql.registerObject(SysRecordShare as never); + await driver.initObjects([DEAL, LINE, 'sys_record_share'].map((name) => ql.getSchema(name) as never)); + + const service = sharing(); + ql.registerMiddleware(buildSharingMiddleware(service) as never, { object: '*' }); + // The engine composes a `ReadableIds` scope from the `security` service: + // here, one whose read filter for an object is the sharing scope. + const services = new Map([['security', { + canReadObject: async () => true, + getReadFilter: (object: string, context: unknown) => service.buildReadFilter(object, context as never), + explain: async () => ({ allowed: true }), + }]]); + await (new ObjectQLPlugin({ ql, registerProtocol: false } as never) as any).init({ + logger: { debug() {}, info() {}, warn() {}, error() {} }, + registerService: (name: string, svc: unknown) => services.set(name, svc), + getService: (name: string) => { + if (!services.has(name)) throw new Error(`Service '${name}' not found`); + return services.get(name); + }, + }); + + const deals: Array> = []; + for (let i = 1; i <= OWNED; i++) deals.push({ id: ownId(i), name: 'seed', owner_id: ME }); + for (let i = 1; i <= 6000; i++) deals.push({ id: shrId(i), name: 'seed', owner_id: OTHER }); + deals.push({ id: QUEUED, name: 'seed', owner_id: null, queue: QUEUE }); + deals.push({ id: QUEUED_ELSEWHERE, name: 'seed', owner_id: null, queue: 'q_other' }); + deals.push({ id: APPROVAL, name: 'seed', owner_id: OTHER }); + for (let i = 1; i <= 50; i++) deals.push({ id: `x_${pad(i)}`, name: 'seed', owner_id: OTHER }); + await knex.batchInsert(DEAL, deals.map((d) => ({ ...d, organization_id: ORG })), 200); + await knex.batchInsert(LINE, deals.map((d) => ({ id: `ln_${d.id}`, name: 'line', deal_id: d.id, organization_id: ORG })), 200); + + // Grants that must never count for the caller on DEAL, and the agent's. + const noise = [ + ...Array.from({ length: 100 }, (_, k) => shareRow(`g_other_${k}`, ownId(k + 1), OTHER, 'edit')), + ...Array.from({ length: 50 }, (_, k) => shareRow(`g_obj_${k}`, `x_${pad(k + 1)}`, ME, 'edit', { object_name: 'd6_elsewhere' })), + shareRow('g_team', NEVER, ME, 'edit', { recipient_type: 'team' }), + ...Array.from({ length: 100 }, (_, k) => shareRow(`g_agent_s${k}`, shrId(k + 1), AGENT, k < 50 ? 'edit' : 'read')), + ...Array.from({ length: 50 }, (_, k) => shareRow(`g_agent_o${k}`, ownId(k + 1), AGENT, 'read')), + ]; + await knex.batchInsert('sys_record_share', noise, 200); + }, 120_000); + + afterAll(async () => { + if (cell.id === 'postgres' && knex) await knex.raw('DROP SCHEMA IF EXISTS ?? CASCADE', [PG_SCHEMA]); + await driver?.disconnect?.(); + }); + + it('PREMISE: the driver evaluates the leaf, and the queue arm is a real column', () => { + expect(driverEvaluatesFixedReadLeaf(driver as never, 'SharedRecordIds')).toBe(true); + expect(resolveInjectedColumnProvenance(ql.getSchema(DEAL) as never, 'queue')).toBe('injected-provisioned'); + }); + + it('5,000 grants: the leaf and today\'s list admit the same rows, list total and get by id, every arm', async () => { + arms = true; + await growGrantsTo(5000); + const expected = OWNED + 5000 + 2; + expect(await leafCount(asMe())).toBe(expected); + expect(await listCount()).toBe(expected); + const viaLeaf = await leafIds(asMe()); + expect(viaLeaf).toHaveLength(expected); + expect(viaLeaf).toEqual(await listIds()); + for (const [id, admitted] of [ + [ownId(1), true], [QUEUED, true], [APPROVAL, true], [shrId(5000), true], + [QUEUED_ELSEWHERE, false], [NEVER, false], [shrId(5001), false], + ] as const) { + expect(await leafGet(id), `leaf · ${id}`).toBe(admitted); + expect(await listGet(id), `list · ${id}`).toBe(admitted); + } + }); + + it('5,000 grants: a predicate update touches the same rows through the write form as through today\'s list', async () => { + arms = true; + const viaLeaf = await leafUpdate(asMe()); + // Owned, queued, and the edit-level grants; never the approval row, never a read-only grant. + expect(viaLeaf).toHaveLength(OWNED + 1 + editGrantsUpTo(5000)); + expect(viaLeaf).toEqual(await listUpdate()); + expect(viaLeaf).not.toContain(APPROVAL); + expect(viaLeaf).not.toContain(shrId(5000)); + }); + + it('5,001 grants: the leaf counts the 5,001st, where today\'s list stops at 5,000', async () => { + arms = false; + await growGrantsTo(5001); + expect(await leafCount(asMe())).toBe(OWNED + 5001); + expect(await listCount(), 'today: one grant dropped without a word').toBe(OWNED + 5000); + expect(await leafGet(shrId(5001))).toBe(true); + }); + + it('6,000 grants: 7,000 rows are visible, and the 6,000th granted record is read by id', async () => { + arms = false; + await growGrantsTo(6000); + expect(await leafCount(asMe())).toBe(7000); + expect(await leafIds(asMe())).toHaveLength(7000); + expect(await leafGet(shrId(6000))).toBe(true); + expect(await listCount(), 'today: 1,000 grants dropped').toBe(OWNED + 5000); + }); + + it('6,000 grants: a predicate update reaches every edit-level grant through the write form', async () => { + arms = false; + const viaLeaf = await leafUpdate(asMe()); + expect(viaLeaf).toHaveLength(OWNED + editGrantsUpTo(6000)); + expect(viaLeaf).toContain(shrId(5999)); + expect(viaLeaf).not.toContain(shrId(6000)); + expect(await listUpdate(), 'today: capped at 5,000 edit grants').toHaveLength(OWNED + 5000); + }); + + it('nested: the leaf inside a composed ReadableIds scope counts every grant', async () => { + arms = false; + const where = { deal_id: { $in: ReadableIds.of(DEAL) } }; + expect(await ql.count(LINE, { where }, { context: asMe() } as never)).toBe(7000); + const sixThousandth = await ql.findOne(LINE, { where: { $and: [{ id: `ln_${shrId(6000)}` }, where] } }, { context: asMe() } as never); + expect(sixThousandth?.deal_id).toBe(shrId(6000)); + const never = await ql.findOne(LINE, { where: { $and: [{ id: `ln_${NEVER}` }, where] } }, { context: asMe() } as never); + expect(never).toBeNull(); + }); + + it('delegated: the agent\'s leaf and the delegator\'s leaf, AND-ed, admit only what both reach', async () => { + arms = false; + // The agent holds 100 grants on shr_*, and 50 on rows the delegator owns. + expect(await leafCount(asAgentForMe())).toBe(150); + expect(await leafGet(shrId(100), asAgentForMe())).toBe(true); + expect(await leafGet(ownId(50), asAgentForMe())).toBe(true); + expect(await leafGet(shrId(101), asAgentForMe()), 'the delegator reaches it, the agent does not').toBe(false); + expect(await leafGet(ownId(51), asAgentForMe()), 'the delegator owns it, the agent holds no grant').toBe(false); + // The write form: the agent's edit grants on shr_0001 … shr_0050, all of which the delegator may edit. + const touched = await leafUpdate(asAgentForMe()); + expect(touched).toEqual(Array.from({ length: 50 }, (_, k) => shrId(k + 1))); + }); + + it('6,000 grants with the queue and approval arms: each is its own disjunct beside the leaf', async () => { + arms = true; + expect(await leafCount(asMe())).toBe(7002); + expect(await leafGet(QUEUED)).toBe(true); + expect(await leafGet(APPROVAL)).toBe(true); + expect(await leafGet(QUEUED_ELSEWHERE)).toBe(false); + }); + }); +} diff --git a/packages/plugins/plugin-sharing/src/shared-record-ids.testkit.ts b/packages/plugins/plugin-sharing/src/shared-record-ids.testkit.ts new file mode 100644 index 00000000000..3e14b51f035 --- /dev/null +++ b/packages/plugins/plugin-sharing/src/shared-record-ids.testkit.ts @@ -0,0 +1,50 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 plan step 6] The share-grant leaf for this package's hand-written + * engine doubles. + * + * From the switch on, the read and bulk-write scopes carry the share arm as + * `{ id: { $in: SharedRecordIds.read(object, user) } }` (or `.write`), a + * branded leaf where an id list used to be. A double whose `$in` arm calls + * `.includes` on its comparand cannot read it, and a double that quietly + * treated it as "no member" would green a scope that admits nothing. So a + * double resolves it here, over its OWN `sys_record_share` rows, under the + * leaf's own fixed inner read (`fixedInnerReadOf`): the predicate is the + * leaf's description, ⛔ never restated in a test. + * + * `.testkit.ts`, not `.test.ts`: it holds no assertions and is not collected + * as a suite. It is imported only by tests, so tsup (entry `src/index.ts`) + * never bundles it into `dist`. + */ + +import { fixedInnerReadOf, isFixedReadLeaf } from '@objectstack/spec/data'; + +/** A row as the doubles store it. */ +type Row = Record; + +/** + * The members `{ $in: comparand }` admits in a double: the array as given, or, + * for a fixed-read leaf, the ids its fixed inner read denotes over `shareRows` + * (the double's `sys_record_share` table): every row whose `equals` columns + * match and whose `memberOf` columns hold one of the listed values, its + * projected column kept when it is neither null nor empty, as each evaluator + * keeps it. Anything else is a comparand the double cannot read, and throws, + * as the engine's comparand door refuses it. + */ +export function inMembers(comparand: unknown, shareRows: readonly Row[] | undefined): readonly unknown[] { + if (Array.isArray(comparand)) return comparand; + if (!isFixedReadLeaf(comparand)) { + throw new TypeError('test double: a `$in` comparand that is neither a list nor a fixed-read leaf'); + } + const read = fixedInnerReadOf(comparand); + const ids: string[] = []; + for (const row of shareRows ?? []) { + if (!Object.entries(read.equals).every(([column, value]) => row[column] === value)) continue; + if (!Object.entries(read.memberOf).every(([column, values]) => values.includes(String(row[column])))) continue; + const id = row[read.column]; + if (id == null || id === '') continue; + ids.push(String(id)); + } + return ids; +} diff --git a/packages/plugins/plugin-sharing/src/sharing-plugin.ts b/packages/plugins/plugin-sharing/src/sharing-plugin.ts index 67b68073f67..830dfebd6b7 100644 --- a/packages/plugins/plugin-sharing/src/sharing-plugin.ts +++ b/packages/plugins/plugin-sharing/src/sharing-plugin.ts @@ -97,6 +97,7 @@ import { createDeclaredSharingRuleSource } from './declared-sharing-rules.js'; import { normalizeTenancyPosture, postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/security'; import { inProcessSessionReadInput } 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 @@ -1250,6 +1251,22 @@ export class SharingServicePlugin implements Plugin { this.mountShareableObjectsRoute(ctx); }); + // [ADR-0155 ② ruled R1 at boot] Registered BEFORE the passes below, so a + // host in D4's second class (a middleware or a find hook registered for + // `sys_record_share` by name) is refused before any of them runs and + // before any request is served (`kernel:listening` has not opened the + // socket). Judged here, not at `kernel:ready`: other plugins register + // their read middlewares and find hooks in their own `kernel:ready` + // handlers, so only now is every registration final. Only where a + // producer writes the leaf: the sharing service is registered, whatever + // `enforce` says, because plugin-security's read paths ask that service + // for its read filter too. See `share-arm-boot.ts`. + ctx.hook('kernel:bootstrapped', async () => { + if (!this.service) return; + const refusal = shareGrantRegistrationRefusal(this.engine as any, ctx.logger as any); + if (refusal) throw refusal; + }); + // [#2926 ③] Materialize sharing grants for rows already present at boot. // [#13533] SeedLoader rows used to be the headline case, because the rule // hooks short-circuited on `isSystem` and so never produced a @@ -1356,6 +1373,20 @@ export class SharingServicePlugin implements Plugin { // from here (see bindRuleRebindTriggers). this.ruleGrantsBootReconciled = true; }); + + // [ADR-0155 ② ruled R2, ADR-0111 D10] The visible trail of the storage + // rows' tightening: the objects whose share grants stopped counting at the + // switch and that hold share rows, named once per boot at `warn`. After + // the passes above, in a handler of its own, so it runs in every posture + // (`enforce: false` and no rule service included) and never fails the boot. + ctx.hook('kernel:bootstrapped', async () => { + if (!this.service) return; + try { + await reportInertShareGrantHolders(this.service, registeredObjectNames(this.engine), ctx.logger as any); + } catch (err: any) { + ctx.logger.warn('SharingServicePlugin: the report of share grants that no longer count (kernel:bootstrapped) failed', { error: err?.message }); + } + }); } } @@ -1524,8 +1555,11 @@ export function buildSharingMiddleware( // card: vouch the caller's own predicate BEFORE the rewrite below // makes it unrecognisable to every later boundary. vouchCallerWhereBeforeRewrite(ast, ctx.options); + // [ADR-0155 plan step 6] `where` only. The scope used to be mirrored + // under the AST's `filter` key too, which the engine's executor seam + // does not walk and no driver reads; it now carries the share-grant + // leaf, which must never sit where the seam does not judge it. ast.where = composeAnd(ast.where, filter); - ast.filter = composeAnd(ast.filter, filter); ctx.ast = ast; } return next(); @@ -1688,8 +1722,10 @@ export function buildSharingMiddleware( } if (writeFilter) { const ast: any = ctx.ast ?? {}; + // [ADR-0155 plan step 6] `where` only, as on the read path above: the + // write form of the share-grant leaf is judged by the seam in a + // predicate update's `where`, and never mirrored under `filter`. ast.where = composeAnd(ast.where, writeFilter); - ast.filter = composeAnd(ast.filter, writeFilter); ctx.ast = ast; } return next(); diff --git a/packages/plugins/plugin-sharing/src/sharing-service.test.ts b/packages/plugins/plugin-sharing/src/sharing-service.test.ts index 3f487664c69..d7ddce54c03 100644 --- a/packages/plugins/plugin-sharing/src/sharing-service.test.ts +++ b/packages/plugins/plugin-sharing/src/sharing-service.test.ts @@ -11,6 +11,14 @@ import { buildSharingMiddleware } from './sharing-plugin.js'; import { bootRequestContext } from './exec-context-seam.testkit.js'; import { SysRecordShare } from './objects/sys-record-share.object.js'; import { SysSharingRule } from './objects/sys-sharing-rule.object.js'; +import { SharedRecordIds, isSharedRecordIds } from '@objectstack/spec/data'; +import { WRITE_ACCESS_LEVELS } from './access-level.js'; +import { inMembers } from './shared-record-ids.testkit.js'; + +/** [ADR-0155 D3] The share arm of a read scope: the leaf, never an id list. */ +const shareArm = (object: string, user: string) => ({ id: { $in: SharedRecordIds.read(object, user) } }); +/** [ADR-0155 D3, ③ ruled A] The share arm of a bulk-update scope: the leaf's write form. */ +const editShareArm = (object: string, user: string) => ({ id: { $in: SharedRecordIds.write(object, user, WRITE_ACCESS_LEVELS) } }); // ───────────────────────────────────────────────────────────────────── // In-memory fake engine @@ -39,7 +47,8 @@ function makeFakeEngine(schemas: Record) { if (k === '$or' || k === '$and') continue; const rv = row[k]; if (v != null && typeof v === 'object' && '$in' in (v as any)) { - if (!(v as any).$in.includes(rv)) return false; + // [ADR-0155] A share-grant leaf resolves over this double's own rows. + if (!inMembers((v as any).$in, tables.sys_record_share).includes(rv)) return false; continue; } if (rv !== v) return false; @@ -183,7 +192,7 @@ describe('SharingService.buildReadFilter', () => { // 张三 (u1) must NOT read 李四's records on an OWD-less custom object: // the read filter narrows to owner_id = u1 instead of passing null. const f = await svc.buildReadFilter('task', { userId: 'u1' }); - expect(f).toEqual({ owner_id: 'u1' }); + expect(f).toEqual({ $or: [{ owner_id: 'u1' }, shareArm('task', 'u1')] }); }); it('[ADR-0090 D1] system object with unset sharingModel keeps the public fall-through', async () => { @@ -193,7 +202,7 @@ describe('SharingService.buildReadFilter', () => { it('[ADR-0090 D4] an unrecognised stored sharingModel fails CLOSED to private', async () => { engine.schemas.legacy = { name: 'legacy', sharingModel: 'read_write', fields: { id: {}, owner_id: {} } } as any; const f = await svc.buildReadFilter('legacy', { userId: 'u1' }); - expect(f).toEqual({ owner_id: 'u1' }); + expect(f).toEqual({ $or: [{ owner_id: 'u1' }, shareArm('legacy', 'u1')] }); }); it('returns null for read-only-sharing objects (writes are gated, reads are not)', async () => { @@ -217,19 +226,21 @@ describe('SharingService.buildReadFilter', () => { expect(f).toEqual({ id: '__deny_all__' }); }); - it('returns owner-only filter when user has no explicit shares', async () => { + it('[ADR-0155 D3] carries the share arm with no grant at all: the statement does not depend on the grant count', async () => { const f = await svc.buildReadFilter('account', { userId: 'alice' }); - expect(f).toEqual({ owner_id: 'alice' }); + expect(f).toEqual({ $or: [{ owner_id: 'alice' }, shareArm('account', 'alice')] }); }); - it('returns owner OR shared-record filter when grants exist', async () => { + it('[ADR-0155 D3] returns owner OR the share-grant leaf, which denotes every grant to the caller', async () => { // Setup grants run as system — grant authorization has its own suite below. await svc.grant({ object: 'account', recordId: 'a1', recipientId: 'alice' }, { isSystem: true }); await svc.grant({ object: 'account', recordId: 'a2', recipientId: 'alice', accessLevel: 'edit' }, { isSystem: true }); + await svc.grant({ object: 'account', recordId: 'a3', recipientId: 'bob' }, { isSystem: true }); const f: any = await svc.buildReadFilter('account', { userId: 'alice' }); - expect(f.$or).toBeDefined(); - expect(f.$or[0]).toEqual({ owner_id: 'alice' }); - expect(f.$or[1].id.$in.sort()).toEqual(['a1', 'a2']); + expect(f).toEqual({ $or: [{ owner_id: 'alice' }, shareArm('account', 'alice')] }); + // The branded leaf, never an unbranded copy (which the engine's door refuses). + expect(isSharedRecordIds(f.$or[1].id.$in)).toBe(true); + expect([...inMembers(f.$or[1].id.$in, engine._tables.sys_record_share)].sort()).toEqual(['a1', 'a2']); }); }); @@ -264,17 +275,18 @@ describe('[#26180] SharingService — the pending approver\'s read', () => { it('ORs the pending-approval record ids in beside the owner-match', async () => { const svc = serviceWith(pendingOn([['a9', ['apr_1']]])); expect(await svc.buildReadFilter('account', { userId: 'alice' })).toEqual({ - $or: [{ owner_id: 'alice' }, { id: { $in: ['a9'] } }], + $or: [{ owner_id: 'alice' }, shareArm('account', 'alice'), { id: { $in: ['a9'] } }], }); expect(asked).toEqual([{ object: 'account', userId: 'alice' }]); }); - it('joins the record shares, once per id', async () => { + it('[ADR-0155 D3] stands as a disjunct of its own beside the share arm, never merged into it', async () => { await new SharingService({ engine }).grant({ object: 'account', recordId: 'a1', recipientId: 'alice' }, { isSystem: true }); const svc = serviceWith(pendingOn([['a1', ['apr_1']], ['a9', ['apr_2']]])); const f: any = await svc.buildReadFilter('account', { userId: 'alice' }); expect(f.$or[0]).toEqual({ owner_id: 'alice' }); - expect([...f.$or[1].id.$in].sort()).toEqual(['a1', 'a9']); + expect(f.$or[1]).toEqual(shareArm('account', 'alice')); + expect(f.$or[2]).toEqual({ id: { $in: ['a1', 'a9'] } }); }); it('never reaches a write gate: an approver on the slate who owns nothing edits and deletes nothing', async () => { @@ -282,7 +294,9 @@ describe('[#26180] SharingService — the pending approver\'s read', () => { await engine.insert('account', { id: 'a9', owner_id: 'bob' }); expect(await svc.canEdit('account', 'a9', { userId: 'alice' })).toBe(false); expect(await svc.canDelete('account', 'a9', { userId: 'alice' })).toBe(false); - expect(await svc.buildWriteFilter('account', { userId: 'alice' })).toEqual({ owner_id: 'alice' }); + expect(await svc.buildWriteFilter('account', { userId: 'alice' })).toEqual({ + $or: [{ owner_id: 'alice' }, editShareArm('account', 'alice')], + }); }); it('is not asked where the read filter imposes nothing, or denies all', async () => { @@ -295,13 +309,13 @@ describe('[#26180] SharingService — the pending approver\'s read', () => { it('grants nothing to an on-behalf-of principal: the grant is the person\'s own (ADR-0090 D10)', async () => { const svc = serviceWith(pendingOn([['a9', ['apr_1']]])); const delegated = { userId: 'agent_1', onBehalfOf: { userId: 'alice' } } as any; - expect(await svc.buildReadFilter('account', delegated)).toEqual({ owner_id: 'agent_1' }); + expect(await svc.buildReadFilter('account', delegated)).toEqual({ $or: [{ owner_id: 'agent_1' }, shareArm('account', 'agent_1')] }); expect(await svc.listApprovalReadGrants('account', 'a9', delegated)).toEqual([]); expect(asked).toEqual([]); }); it('fails closed: no service, no member, a throwing lookup or a rejected read all grant nothing', async () => { - const ownerOnly = { owner_id: 'alice' }; + const ownerOnly = { $or: [{ owner_id: 'alice' }, shareArm('account', 'alice')] }; const warn = vi.fn(); const variants: Array = [ undefined, @@ -712,7 +726,10 @@ describe('buildSharingMiddleware (engine integration)', () => { context: { userId: 'alice' }, }; await mw(ctx, async () => {}); - expect(ctx.ast.where).toEqual({ owner_id: 'alice' }); + expect(ctx.ast.where).toEqual({ $or: [{ owner_id: 'alice' }, shareArm('account', 'alice')] }); + // [ADR-0155 plan step 6] The scope lands in `where` only: never mirrored + // under `filter`, which the engine's executor seam does not walk. + expect(ctx.ast.filter).toBeUndefined(); }); it('skips read filter for system context', async () => { @@ -849,7 +866,10 @@ describe('buildSharingMiddleware (engine integration)', () => { context: { userId: 'bob' }, }; await mw(ctx, async () => {}); - expect(ctx.ast.where).toEqual({ $or: [{ owner_id: 'bob' }, { id: { $in: ['a2'] } }] }); + expect(ctx.ast.where).toEqual({ $or: [{ owner_id: 'bob' }, editShareArm('account', 'bob')] }); + expect(inMembers((ctx.ast.where as any).$or[1].id.$in, engine._tables.sys_record_share)).toEqual(['a2']); + // [ADR-0155 plan step 6] …and the write scope is not mirrored under `filter` either. + expect(ctx.ast.filter).toBeUndefined(); }); it('does not block insert', async () => { @@ -874,7 +894,7 @@ describe('buildSharingMiddleware (engine integration)', () => { context: { userId: 'alice' }, }; await mw(ctx, async () => {}); - expect(ctx.ast.where).toEqual({ $and: [{ name: 'Acme' }, { owner_id: 'alice' }] }); + expect(ctx.ast.where).toEqual({ $and: [{ name: 'Acme' }, { $or: [{ owner_id: 'alice' }, shareArm('account', 'alice')] }] }); }); // ─── Bulk (multi) write owner scoping (#2982) ─────────────────── @@ -891,8 +911,8 @@ describe('buildSharingMiddleware (engine integration)', () => { let nextCalled = false; await mw(ctx, async () => { nextCalled = true; }); expect(nextCalled).toBe(true); - // bob's bulk update is constrained to rows bob owns. - expect(ctx.ast.where).toEqual({ $and: [{ name: 'X' }, { owner_id: 'bob' }] }); + // bob's bulk update is constrained to rows bob owns, or edit-shares to bob. + expect(ctx.ast.where).toEqual({ $and: [{ name: 'X' }, { $or: [{ owner_id: 'bob' }, editShareArm('account', 'bob')] }] }); }); it('bulk delete: injects the owner filter (no single id to canEdit-gate)', async () => { @@ -920,7 +940,8 @@ describe('buildSharingMiddleware (engine integration)', () => { context: { userId: 'bob' }, }; await mw(ctx, async () => {}); - expect(ctx.ast.where).toEqual({ $or: [{ owner_id: 'bob' }, { id: { $in: ['a1'] } }] }); + expect(ctx.ast.where).toEqual({ $or: [{ owner_id: 'bob' }, editShareArm('account', 'bob')] }); + expect(inMembers((ctx.ast.where as any).$or[1].id.$in, engine._tables.sys_record_share)).toEqual(['a1']); }); it('bulk update on a public_read (read) object is STILL owner-write-scoped', async () => { @@ -938,7 +959,7 @@ describe('buildSharingMiddleware (engine integration)', () => { context: { userId: 'bob' }, }; await mw(ctx, async () => {}); - expect(ctx.ast.where).toEqual({ owner_id: 'bob' }); + expect(ctx.ast.where).toEqual({ $or: [{ owner_id: 'bob' }, editShareArm('lead', 'bob')] }); }); it('bulk update: system context is unrestricted', async () => { @@ -1686,7 +1707,7 @@ describe('[#5859] resolveOwnerScopeIds fills the AUTHORITATIVE organization', () // The bulk path reads the same owner set — dana must not be in it. const filter: any = await svc.buildWriteFilter('account', bob, 'update'); - expect(filter).toEqual({ owner_id: { $in: ['alice', 'bob'] } }); + expect(filter).toEqual({ $or: [{ owner_id: { $in: ['alice', 'bob'] } }, editShareArm('account', 'bob')] }); }); // ── [ADR-0105 D1] The posture fork on "no active organization" ──────── @@ -2085,19 +2106,19 @@ describe('[#6428] the boolean projection does not drift (compatibility clause)', // ───────────────────────────────────────────────────────────────────── -describe('[#13551] the record-share `$in` drops nullish `record_id` rows', () => { - // The guard standing in front of BOTH `$in` constructions used to read - // `.map((g) => String(g.record_id)).filter(Boolean)`, which cannot drop a - // nullish `record_id`: `String(null)` is `'null'`, `String(undefined)` is - // `'undefined'`, and both are truthy. What follows pins the MECHANISM — a - // row with no `record_id` contributes no member — and asserts nothing about - // whether such a row exists in the wild. +describe('[#13551 → ADR-0155] the scopes read no grant row: a nullish `record_id` is the evaluator\'s to drop', () => { + // #13551 repaired the guard in front of the id list both scopes used to + // bind: a row with a nullish `record_id` contributed no member. From the + // switch on there is no list to guard. Both scopes carry the share-grant + // leaf, which this service builds without reading `sys_record_share` at all, + // and the guard moved into the leaf's fixed inner read, which every + // evaluator runs (`record_id IS NOT NULL AND record_id <> ''` on SQL, + // pinned per dialect in driver-sql; and against a real SQLite table in + // `shared-record-ids-switch.test.ts`, where a corrupt row admits nothing). // // The rows are seeded straight into the fake table on purpose: `grant()` // refuses a nullish `recordId` at the front door, so writing the row - // directly is the only way to stand up the already-corrupt state the guard - // exists for — the shape a bad backfill or an out-of-band - // `sys_record_share` write would leave behind. + // directly is the only way to stand up the already-corrupt state. let engine: ReturnType; let svc: SharingService; @@ -2107,7 +2128,7 @@ describe('[#13551] the record-share `$in` drops nullish `record_id` rows', () => record_id, recipient_type: 'user', recipient_id: 'alice', - access_level: 'edit', // in WRITE_ACCESS_LEVELS, so the write filter reads it too + access_level: 'edit', // in WRITE_ACCESS_LEVELS, so the write form denotes it too }); beforeEach(() => { @@ -2118,50 +2139,20 @@ describe('[#13551] the record-share `$in` drops nullish `record_id` rows', () => svc = new SharingService({ engine }); }); - it('read filter: a null / undefined `record_id` contributes NO member, and the real grant survives', async () => { - engine._tables.sys_record_share = [shareRow('a1'), shareRow(null), shareRow(undefined)]; - const f: any = await svc.buildReadFilter('account', { userId: 'alice' }); - expect(f.$or[1].id.$in).toEqual(['a1']); - // Named literally: these are the two members the dead guard used to emit. - expect(f.$or[1].id.$in).not.toContain('null'); - expect(f.$or[1].id.$in).not.toContain('undefined'); - }); - - it('write filter: the same rows, the same outcome — both construction sites are repaired', async () => { - engine._tables.sys_record_share = [shareRow('a1'), shareRow(null), shareRow(undefined)]; - const f: any = await svc.buildWriteFilter('account', { userId: 'alice' }, 'update'); - expect(f.$or[1].id.$in).toEqual(['a1']); - expect(f.$or[1].id.$in).not.toContain('null'); - expect(f.$or[1].id.$in).not.toContain('undefined'); - }); - - it('when EVERY grant is nullish the share branch disappears, on both filters', async () => { - engine._tables.sys_record_share = [shareRow(null), shareRow(undefined)]; - // Not an `$or` carrying a member that matches nothing: zero usable grants - // collapses to the owner match, which is what "no grants" already meant. - expect(await svc.buildReadFilter('account', { userId: 'alice' })) - .toEqual({ owner_id: 'alice' }); - expect(await svc.buildWriteFilter('account', { userId: 'alice' }, 'update')) - .toEqual({ owner_id: 'alice' }); - }); - - it('over-denial control: an ordinary grant set still produces exactly its ids, on both filters', async () => { - engine._tables.sys_record_share = [shareRow('a1'), shareRow('a2'), shareRow('a3')]; - const read: any = await svc.buildReadFilter('account', { userId: 'alice' }); - const write: any = await svc.buildWriteFilter('account', { userId: 'alice' }, 'update'); - expect(read.$or[0]).toEqual({ owner_id: 'alice' }); - expect(write.$or[0]).toEqual({ owner_id: 'alice' }); - expect(read.$or[1].id.$in).toEqual(['a1', 'a2', 'a3']); - expect(write.$or[1].id.$in).toEqual(['a1', 'a2', 'a3']); - }); - - it('the non-null path is unchanged: a driver-numeric id still stringifies, an empty string is still dropped', async () => { - engine._tables.sys_record_share = [shareRow(42), shareRow(''), shareRow('a1')]; - const f: any = await svc.buildReadFilter('account', { userId: 'alice' }); - // `42` becomes `'42'` exactly as `String()` always made it, and `''` — the - // one value the old `.filter(Boolean)` could actually drop — is still - // dropped. Only the nullish rows are newly excluded. - expect(f.$or[1].id.$in).toEqual(['42', 'a1']); + it('corrupt, numeric, ordinary or no grant rows: both scopes are the same leaf, built without reading a row', async () => { + const tables = [ + [], + [shareRow('a1'), shareRow(null), shareRow(undefined)], + [shareRow(null), shareRow(undefined)], + [shareRow(42), shareRow(''), shareRow('a1')], + ]; + for (const rows of tables) { + engine._tables.sys_record_share = rows; + expect(await svc.buildReadFilter('account', { userId: 'alice' })) + .toEqual({ $or: [{ owner_id: 'alice' }, shareArm('account', 'alice')] }); + expect(await svc.buildWriteFilter('account', { userId: 'alice' }, 'update')) + .toEqual({ $or: [{ owner_id: 'alice' }, editShareArm('account', 'alice')] }); + } }); }); diff --git a/packages/plugins/plugin-sharing/src/sharing-service.ts b/packages/plugins/plugin-sharing/src/sharing-service.ts index 865061d0017..d1bf713b298 100644 --- a/packages/plugins/plugin-sharing/src/sharing-service.ts +++ b/packages/plugins/plugin-sharing/src/sharing-service.ts @@ -12,8 +12,9 @@ import type { ShareAccessLevel, SharingWriteVerdict, IOwnershipQueueService, + EngineFixedReadLeafClass, } from '@objectstack/spec/contracts'; -import { resolveInjectedColumnProvenance } from '@objectstack/spec/data'; +import { SharedRecordIds, resolveInjectedColumnProvenance } from '@objectstack/spec/data'; import { normalizeTenancyPosture, postureEnforcesWall, @@ -30,7 +31,9 @@ import { PLATFORM_CAPABILITY_PROVIDERS, type ExecutionContext } from '@objectsta // [commit 3f64fe6c6] The engine's own answer to "which column is this object walled // by?" — the twin of `SqlDriver.computeTenantField`, so the organization a grant // is stamped from is read off the SAME column the wall scopes the record by. -import { resolveTenantFieldName } from '@objectstack/objectql'; +// [ADR-0155 ② ruled R2] …and the one reader of a driver's `fixedReadLeaves` +// declaration, the seam's own: whether the share arm can run on an object. +import { driverEvaluatesFixedReadLeaf, resolveTenantFieldName } from '@objectstack/objectql'; // [Ruling of record 6355206139] The EXTERNAL rung's OWD floor — the stamp // plugin-security makes and this service reads, named once in core. import { owdForAudience } from '@objectstack/core'; @@ -73,6 +76,21 @@ export interface SharingEngine { * `.password_hash`. */ resolveInternalField?(object: string, recordIds: readonly string[], field: string): Promise>; + /** + * [ADR-0155 ② ruled R2] The driver `object` dispatches to + * (`IDataEngine.getDriverForObject`): its `supports.fixedReadLeaves` says + * whether it evaluates the share arm ({@link SharingService.shareGrantsInertReason}). + * Optional: an engine without it cannot say, and the share arm is written, + * with the engine seam's refusal behind it. + */ + getDriverForObject?(object: string): { readonly name?: unknown; readonly supports?: unknown } | undefined; + /** + * [ADR-0155 D4] `IObjectQLEngine.fixedReadLeafClassOf`: which of D4's two + * classes a share-grant leaf falls in on this engine, `null` for neither. + * Read for the object on another datasource (R2) and for the host class at + * boot (R1). Optional: an engine without it cannot say. + */ + fixedReadLeafClassOf?(leaf: SharedRecordIds): EngineFixedReadLeafClass | null; } /** @@ -368,41 +386,17 @@ function hasQueueColumn(schema: any): boolean { return resolveInjectedColumnProvenance(schema, QUEUE_FIELD) === 'injected-provisioned'; } -/** - * The `record_id` column of a `sys_record_share` read, as the members of a - * security `$in`. A row whose `record_id` is nullish or empty contributes - * NOTHING — the nullish test runs on the RAW column value, BEFORE `String()`. - * - * The order is the whole point. The previous spelling coerced first and - * filtered after — `grants.map((g) => String(g.record_id)).filter(Boolean)` — - * which cannot drop a nullish `record_id` at all: `String(null)` is `'null'` - * and `String(undefined)` is `'undefined'`, and both are truthy. The only - * value it could drop was the empty string, so the guard was dead for exactly - * the case its spelling advertised, and a corrupt row put the literal string - * `'null'` into `{ id: { $in: [...] } }`. Both call sites are positive - * polarity (an OR-ed branch, never negated) and no real record id matches that - * member, so the effect was a silently DROPPED grant rather than a widened - * scope — but an audit asking which security paths already handle nullish ids - * would have counted these two as covered when they provably were not. - * - * `String()` is kept for the surviving values: a driver may hand back a - * numeric primary key, and the members must compare against the string ids the - * rest of the filter is built from. Every non-nullish value therefore - * stringifies exactly as it did before, and the trailing `!== ''` drops - * precisely what `filter(Boolean)` used to drop — so the non-null path is - * unchanged and only the nullish rows are newly excluded. - */ /** [#26180] No pending approval grants a read: the fail-closed answer. */ const NO_APPROVAL_GRANTS: ReadonlyMap = new Map(); -function grantedRecordIds(grants: unknown): string[] { - if (!Array.isArray(grants)) return []; - return grants - .map((g: any) => g?.record_id) - .filter((recordId: unknown) => recordId != null) - .map((recordId: unknown) => String(recordId)) - .filter((recordId: string) => recordId !== ''); -} +/** + * [ADR-0155 ② ruled R2] The recipient of the leaf {@link SharingService.shareGrantsInertReason} + * builds only to ask the engine which of D4's classes an object's share arm + * falls in. The recognition reads the leaf's object and its inner table, never + * its recipient, and this leaf is never placed in a scope or handed to any + * evaluator, so no principal's id is needed or used. + */ +const SHARE_ARM_CLASS_PROBE_RECIPIENT = 'share-arm-class-probe'; /** * [#8418] The one WARN line a write gate emits when it refuses because the @@ -815,30 +809,31 @@ export class SharingService implements ISharingService { ? { [OWNER_FIELD]: ownerIds[0] } : { [OWNER_FIELD]: { $in: ownerIds } }; - const grants = await this.engine.find('sys_record_share', { - where: { - object_name: object, - recipient_type: 'user', - recipient_id: context.userId, - }, - fields: ['record_id', 'access_level'], - limit: 5000, - context: SYSTEM_CTX, - }); - - // [#26180] …and the records a pending approval step waits on the caller - // for: READ only (no write gate reads this), only while the step is - // pending, never across organizations — the approvals service's rules. - const approvalIds = [...(await this.pendingApproverReadGrants(object, context)).keys()]; - const grantedIds: string[] = approvalIds.length === 0 - ? grantedRecordIds(grants) - : [...new Set([...grantedRecordIds(grants), ...approvalIds])]; // [ADR-0142 D3] Beside the owner match: the records sitting in a queue the // caller belongs to. const queueMatch = await this.queueSittingMatch(schema, context); const disjuncts: unknown[] = [ownerMatch]; if (queueMatch) disjuncts.push(queueMatch); - if (grantedIds.length > 0) disjuncts.push({ id: { $in: grantedIds } }); + // [ADR-0155 D3] The records shared to the caller, as the share-grant leaf: + // the engine hands it to the driver, which evaluates it as a semi-join on + // `sys_record_share` under the fixed predicate (object, `user`, the + // caller), so EVERY grant counts, whatever their number, and no grant is + // read into memory here. It replaces the id list this read used to bind, + // which stopped at 5,000 grants and dropped the rest without a word. Always + // present on a sharing-scoped read, whether or not the caller holds a + // grant (the statement does not depend on the grant count), except where + // share grants do not count on the object at all (② ruled R2, + // {@link shareGrantsInertReason}). + if (this.shareGrantsInertReason(object) === null) { + disjuncts.push({ id: { $in: SharedRecordIds.read(object, context.userId) } }); + } + // [#26180] …and the records a pending approval step waits on the caller + // for: READ only (no write gate reads this), only while the step is + // pending, never across organizations — the approvals service's rules. + // [ADR-0155 D3] A disjunct of its own: the approvals service vouches for + // these ids, and they are never share grants. + const approvalIds = [...(await this.pendingApproverReadGrants(object, context)).keys()]; + if (approvalIds.length > 0) disjuncts.push({ id: { $in: approvalIds } }); return disjuncts.length === 1 ? ownerMatch : { $or: disjuncts }; } @@ -937,25 +932,21 @@ export class SharingService implements ISharingService { // drops the share branch. Update keeps the share widening. if (verb === 'delete') return ownerMatch; - const grants = await this.engine.find('sys_record_share', { - where: { - object_name: object, - recipient_type: 'user', - recipient_id: context.userId, - access_level: { $in: [...WRITE_ACCESS_LEVELS] }, - }, - fields: ['record_id'], - limit: 5000, - context: SYSTEM_CTX, - }); - const grantedIds: string[] = grantedRecordIds(grants); // [ADR-0142 D3] The update arm only: a queue member edits what sits in the // queue and deletes none of it (rows, never verbs — the delete arm above // returned before this line). const queueMatch = await this.queueSittingMatch(schema, context); const disjuncts: unknown[] = [ownerMatch]; if (queueMatch) disjuncts.push(queueMatch); - if (grantedIds.length > 0) disjuncts.push({ id: { $in: grantedIds } }); + // [ADR-0155 D3, ③ ruled A] The records shared to the caller at a + // {@link WRITE_ACCESS_LEVELS} level, as the leaf's write form: the engine + // admits it in the `where` of a predicate `update` only, and the driver + // evaluates it in each of that update's statements, the prior-row read and + // the write. Uncapped, like the read form; absent where share grants do + // not count on the object (② ruled R2). + if (this.shareGrantsInertReason(object) === null) { + disjuncts.push({ id: { $in: SharedRecordIds.write(object, context.userId, WRITE_ACCESS_LEVELS) } }); + } return disjuncts.length === 1 ? ownerMatch : { $or: disjuncts }; } @@ -1247,8 +1238,11 @@ export class SharingService implements ISharingService { // 1) Ownership (write DEPTH widens the owner-set) — fast path. if (await this.matchesOwnerScope(object, recordId, context)) return 'allow'; - // 2) Explicit write-level share (`edit`, plus not-yet-normalised `full`). - const editGrants = await this.engine.find('sys_record_share', { + // 2) Explicit write-level share (`edit`, plus not-yet-normalised `full`), + // [ADR-0155 ② ruled R2] on an object where share grants count: where they + // do not, the read and bulk-write scopes carry no share arm, so this gate + // reads no grant row either, and the three cannot disagree. + const editGrants = this.shareGrantsInertReason(object) !== null ? [] : await this.engine.find('sys_record_share', { where: { object_name: object, record_id: recordId, @@ -1721,6 +1715,102 @@ export class SharingService implements ISharingService { } } + /** + * [ADR-0155 ② ruled R2] Why share grants do not count on `object`, or `null` + * when they do. + * + * From the switch on, a sharing-scoped read carries the share arm as the + * `SharedRecordIds` leaf, which only an evaluator that runs it can answer. + * ② ruled R2 for the storage that cannot: an object bound to another + * datasource than `sys_record_share` (D4's first class, the engine's own + * recognition, `fixedReadLeafClassOf`), and an object whose driver does not + * list the leaf in its `supports.fixedReadLeaves` (the seam's own reader, + * `driverEvaluatesFixedReadLeaf`). There the producer writes no share arm, + * `checkEdit` reads no grant row, and the grant door and the sharing-rule + * save door refuse a new grant as inert (ADR-0111 D7, `SHARING_NOT_ENABLED` + * / 422). Owner, queue and approval access are unchanged. A leaf that still + * reaches such an evaluator is refused by the engine seam (R1 behind R2). + * + * `null` also when the engine cannot say (no `getDriverForObject`, or one + * that throws): the share arm is then written, and the seam is the answer + * behind it. A recognition that throws counts as no answer, never as a + * class. An engine that answers with no driver for the object answers R2: + * nothing could evaluate the arm there. + * + * Asked per call, never cached: a datasource binding can change after boot, + * and both readings are the ones the engine seam itself makes on every read + * that carries the leaf. + */ + shareGrantsInertReason(object: string): string | null { + let recognised: EngineFixedReadLeafClass | null | undefined; + try { + recognised = this.engine.fixedReadLeafClassOf?.(SharedRecordIds.read(object, SHARE_ARM_CLASS_PROBE_RECIPIENT)); + } catch { + recognised = undefined; + } + if (recognised?.class === 'other-datasource') { + return `'${object}' is bound to datasource '${String(recognised.objectDatasource)}' while '${recognised.table}' ` + + `is bound to '${String(recognised.tableDatasource)}': no driver evaluates a share grant across two ` + + 'datasources, so a share row on it would never be consulted (ADR-0155 R2)'; + } + if (typeof this.engine.getDriverForObject !== 'function') return null; + let driver: ReturnType>; + try { + driver = this.engine.getDriverForObject(object); + } catch { + return null; + } + if (driverEvaluatesFixedReadLeaf(driver, 'SharedRecordIds')) return null; + const name = typeof driver?.name === 'string' && driver.name !== '' ? driver.name : 'unknown'; + return `'${object}' is stored by driver '${name}', which does not evaluate a share grant (its ` + + 'supports.fixedReadLeaves does not list SharedRecordIds), so a share row on it would never be ' + + 'consulted (ADR-0155 R2)'; + } + + /** + * [ADR-0155 ② ruled R2] Of `objects`, the ones whose share grants stopped + * counting at the switch and that hold `sys_record_share` rows, each with + * {@link shareGrantsInertReason}'s reason: the instrument of the boot report + * ADR-0111 D10 asks for (`share-arm-boot.ts`). + * + * "Stopped" is literal: an object where no share row was consulted before + * the switch either (a bypass-listed internal, a `controlled_by_parent` + * detail, an object with no `owner_id`, a federated object whose `owner_id` + * is the injected anchor) is not named, since nothing changed for it. Each + * remaining object costs one `limit 1` system read of `sys_record_share`; + * an object where share grants count costs none. A read that fails leaves + * its object out, logged at `warn`. + */ + async inertShareGrantHolders(objects: readonly string[]): Promise> { + const holders: Array<{ object: string; reason: string }> = []; + for (const object of objects) { + if (this.bypassObjects.has(object)) continue; + const schema = this.engine.getSchema?.(object); + if (!schema || !hasOwnerField(schema) || hasPhantomOwnerAnchor(schema)) continue; + if ((schema?.sharingModel ?? schema?.security?.sharingModel) === 'controlled_by_parent') continue; + const reason = this.shareGrantsInertReason(object); + if (reason === null) continue; + try { + const rows = await this.engine.find('sys_record_share', { + where: { object_name: object }, + fields: ['id'], + limit: 1, + context: SYSTEM_CTX, + }); + if (Array.isArray(rows) && rows.length > 0) holders.push({ object, reason }); + } catch (err) { + // Left out of the list, and said so: the report is an instrument, + // never a gate, but a holder it could not read is not a non-holder. + this.logger?.warn?.( + `[sharing] could not read whether '${object}' holds share rows whose grants no longer count ` + + '(ADR-0155 R2); it is left out of the boot report', + { object, error: err instanceof Error ? err.message : String(err) }, + ); + } + } + return holders; + } + /** * [ADR-0111 D7] Would a `sys_record_share` row on `object` ever be consulted * by a read/write decision? Returns the REASON it could not be, or `null` @@ -1773,6 +1863,14 @@ export class SharingService implements ISharingService { if (declared === 'controlled_by_parent') { return `'${object}' is controlled by its parent (master-detail); share the master record instead`; } + // [ADR-0155 ② ruled R2] ADR-0111 D7's arm for the storage rows: no gate + // consults a share row on an object whose storage cannot evaluate the share + // arm. Asked before the model and the anchor, because it holds whatever + // they are: neither a private model nor a declared remote owner column + // makes such a row count, and for the external population on a public + // model it is the one reason that applies. + const shareArm = this.shareGrantsInertReason(object); + if (shareArm) return shareArm; const isPublic = effectiveSharingModel(schema) === 'public'; if (isPublic || !hasOwnerField(schema)) { // [#25549] The external floor composes over `owner_id`, so the arm can lift @@ -1885,6 +1983,10 @@ export class SharingService implements ISharingService { if (declared === 'controlled_by_parent') { return 'Author the rule on its master object instead.'; } + if (this.shareGrantsInertReason(object)) { + return `To use sharing rules on it, store '${object}' on the datasource of 'sys_record_share', on a driver ` + + 'that evaluates share grants (the SQL drivers do).'; + } // Asked before the model: a federated object whose `owner_id` is the // injected anchor already HAS that field, public or not, and a private // model would still meet the phantom-anchor refusal. diff --git a/packages/plugins/plugin-sharing/src/system-caller-inert-grant.test.ts b/packages/plugins/plugin-sharing/src/system-caller-inert-grant.test.ts index 6304bcc8b91..fc26705fb02 100644 --- a/packages/plugins/plugin-sharing/src/system-caller-inert-grant.test.ts +++ b/packages/plugins/plugin-sharing/src/system-caller-inert-grant.test.ts @@ -63,6 +63,8 @@ import { } from '@objectstack/metadata-core'; import { ERROR_CODE_LEDGER } from '@objectstack/spec/api'; import { SharingService } from './sharing-service.js'; +import { inMembers } from './shared-record-ids.testkit.js'; +import { SharedRecordIds } from '@objectstack/spec/data'; import { SharingRuleService } from './sharing-rule-service.js'; import { backfillRuleGrants } from './sharing-plugin.js'; @@ -82,7 +84,8 @@ function makeEngine(schemas: Record) { if (k === '$or' || k === '$and') continue; const rv = row[k]; if (v != null && typeof v === 'object' && '$in' in (v as any)) { - if (!(v as any).$in.includes(rv)) return false; + // [ADR-0155] A share-grant leaf resolves over this double's own share rows. + if (!inMembers((v as any).$in, tables.sys_record_share).includes(rv)) return false; continue; } if (rv !== v) return false; @@ -378,7 +381,7 @@ describe('[#8207] the sharing-rule evaluator can no longer materialise inert row // LIVE: the criteria-matched record is reachable, the unmatched one is not. expect(await sharing.canEdit('account', 'r1', { userId: 'usr_grantee' } as any)).toBe(false); // read-level grant const filter: any = await sharing.buildReadFilter('account', { userId: 'usr_grantee' } as any); - expect(filter.$or[1].id.$in).toEqual(['r1']); + expect(inMembers(filter.$or[1].id.$in, engine._tables.sys_record_share)).toEqual(['r1']); }); it('the boot backfill still COMPLETES — one bad rule does not stop its siblings', async () => { @@ -477,9 +480,11 @@ describe('[#25549] a public object admits a share to an external member of the r ).resolves.toMatchObject({ object_name: 'board', recipient_id: 'usr_ext', organization_id: 'org_a' }); // The floored external reads the row it was handed beside the (empty) owner arm, // and not b2, which nobody shared to it. - expect(await svc.buildReadFilter('board', externalIn('org_a', 'usr_ext'))).toEqual({ - $or: [{ owner_id: 'usr_ext' }, { id: { $in: ['b1'] } }], + const filter: any = await svc.buildReadFilter('board', externalIn('org_a', 'usr_ext')); + expect(filter).toEqual({ + $or: [{ owner_id: 'usr_ext' }, { id: { $in: SharedRecordIds.read('board', 'usr_ext') } }], }); + expect(inMembers(filter.$or[1].id.$in, engine._tables.sys_record_share)).toEqual(['b1']); }); it('an INTERNAL recipient keeps the 422 — the row would never be consulted for it', async () => { diff --git a/packages/plugins/plugin-sharing/src/system-write-materialisation.test.ts b/packages/plugins/plugin-sharing/src/system-write-materialisation.test.ts index c3ffb45ae5a..2b01dfb567e 100644 --- a/packages/plugins/plugin-sharing/src/system-write-materialisation.test.ts +++ b/packages/plugins/plugin-sharing/src/system-write-materialisation.test.ts @@ -49,6 +49,8 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql'; import { SharingService } from './sharing-service.js'; +import { inMembers } from './shared-record-ids.testkit.js'; +import { SharedRecordIds } from '@objectstack/spec/data'; import { SharingRuleService } from './sharing-rule-service.js'; import { bindRuleHooks, @@ -100,7 +102,8 @@ function makeEngine() { if (k === '$or' || k === '$and') continue; const rv = row[k]; if (v != null && typeof v === 'object' && '$in' in (v as any)) { - if (!(v as any).$in.includes(rv)) return false; + // [ADR-0155] A share-grant leaf resolves over this double's own share rows. + if (!inMembers((v as any).$in, tables.sys_record_share).includes(rv)) return false; continue; } if (rv !== v) return false; @@ -371,7 +374,9 @@ describe('#13533 a system write materialises sharing grants', () => { expect(await rep2CanSee()).toBe(false); // Not because sharing is off: rep2 is simply not the owner and the rule's // criteria is not satisfied yet. - expect(await sharing.buildReadFilter('crm_leave_request', REP2)).toEqual({ owner_id: 'rep2' }); + expect(await sharing.buildReadFilter('crm_leave_request', REP2)).toEqual({ + $or: [{ owner_id: 'rep2' }, { id: { $in: SharedRecordIds.read('crm_leave_request', 'rep2') } }], + }); }); it('SEES it the moment the approval write-back lands — no evaluate, no restart', async () => { @@ -383,9 +388,13 @@ describe('#13533 a system write materialises sharing grants', () => { expect(await rep2CanSee()).toBe(true); // The grant is what widened the filter — the owner match is still there, // so this is additive access, not a scope escalation. - expect(await sharing.buildReadFilter('crm_leave_request', REP2)).toEqual({ - $or: [{ owner_id: 'rep2' }, { id: { $in: ['lr1'] } }], + // The filter itself is the same leaf before and after (ADR-0155): what + // changed is the grant row it denotes, which the double resolves. + const filter: any = await sharing.buildReadFilter('crm_leave_request', REP2); + expect(filter).toEqual({ + $or: [{ owner_id: 'rep2' }, { id: { $in: SharedRecordIds.read('crm_leave_request', 'rep2') } }], }); + expect(inMembers(filter.$or[1].id.$in, engine._tables.sys_record_share)).toEqual(['lr1']); }); it('the approver keeps seeing it either way — a manager view CANNOT observe this defect', async () => { diff --git a/scripts/adr-anchors/packages__plugins__plugin-sharing__src__share-arm-boot.ts.json b/scripts/adr-anchors/packages__plugins__plugin-sharing__src__share-arm-boot.ts.json new file mode 100644 index 00000000000..07febfdbba5 --- /dev/null +++ b/scripts/adr-anchors/packages__plugins__plugin-sharing__src__share-arm-boot.ts.json @@ -0,0 +1,8 @@ +{ + "file": "packages/plugins/plugin-sharing/src/share-arm-boot.ts", + "adrs": [ + "ADR-0111", + "ADR-0155" + ], + "invariant": "The two boot-time answers that land with the share-grant leaf (ADR-0155 plan step 6). R1 at boot: a host that registers an object-scoped middleware, or a beforeFind or afterFind hook, for sys_record_share BY NAME has its boot refused with D4's envelope (INTERNAL_ERROR / 500, fixedReadLeafRefusal) before any request is served; the class is kept whole, with no exemption for a registration that skips system reads, and a registration naming no object or '*' is outside it. The recognition is the engine's own (IObjectQLEngine.fixedReadLeafClassOf), never restated here. R2's report: every object whose storage cannot evaluate the leaf and that holds sys_record_share rows is named once at warn (ADR-0111 D10's visible trail); it never fails the boot." +} diff --git a/scripts/adr-anchors/packages__plugins__plugin-sharing__src__sharing-service.ts.json b/scripts/adr-anchors/packages__plugins__plugin-sharing__src__sharing-service.ts.json new file mode 100644 index 00000000000..fffb0a2c3ff --- /dev/null +++ b/scripts/adr-anchors/packages__plugins__plugin-sharing__src__sharing-service.ts.json @@ -0,0 +1,8 @@ +{ + "file": "packages/plugins/plugin-sharing/src/sharing-service.ts", + "adrs": [ + "ADR-0111", + "ADR-0155" + ], + "invariant": "buildReadFilter and buildWriteFilter write the share arm as the share-grant leaf ({ id: { $in: SharedRecordIds.read(object, user) } }, or .write(object, user, WRITE_ACCESS_LEVELS) on the update scope), never an id list read from sys_record_share, so every grant counts at any count (ADR-0155 D3, Q2 ruled). The approval ids stand as a disjunct of their own; delete scopes to the owner match alone. On an object whose storage cannot evaluate the leaf (shareGrantsInertReason: another datasource than sys_record_share, or a driver that does not declare SharedRecordIds) share grants do not count at all: no scope carries the arm, checkEdit consults no grant, and the grant door and the sharing-rule save door refuse with SHARING_NOT_ENABLED (ADR-0155 R2, ADR-0111 D7). Do not reintroduce a capped grant read, and do not read the grants into memory as a fallback." +} From 8c94ebc0e6e37e06e8b69770da6643d22eaf231c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 06:46:32 +0000 Subject: [PATCH 2/8] test(plugin-security): resolve the share-grant leaf where the scoped where reaches the double Two engine doubles resolved the leaf inside their own `find`, which check:objectql-double-limit cannot drive: it lifts a `find` double out of its file, and the imported resolver call in its body is stubbed, so both doubles read UNJUDGED and the gate's baseline would have grown. Each double's `find` is back to its base text, and the leaf is resolved once for the statement at the request path that hands the scoped `where` to it. The testkit's header says where to call it. Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz Co-authored-by: Claude --- .../src/explain-dependency-fault.test.ts | 18 ++++++++++++------ .../src/explain-read-verdict-inputs.test.ts | 11 +++++++---- .../src/shared-record-ids-in-memory.testkit.ts | 5 +++++ 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/packages/plugins/plugin-security/src/explain-dependency-fault.test.ts b/packages/plugins/plugin-security/src/explain-dependency-fault.test.ts index f475f2dac52..6eac559aa82 100644 --- a/packages/plugins/plugin-security/src/explain-dependency-fault.test.ts +++ b/packages/plugins/plugin-security/src/explain-dependency-fault.test.ts @@ -153,16 +153,13 @@ function makeEngine(schema: Record, storeFaults: ReadonlyMap middlewares.push(mw), getSchema: (name: string) => (name === OBJECT ? schema : undefined), async find(object: string, options: any = {}) { const rows = (tables[object] ??= []); - // [ADR-0155 plan step 6] The share-grant leaf, resolved once for the - // statement as the driver's semi-join is: with the share store down, the - // statement fails on that fault, whichever arm the row would match. - const where = resolveFixedReadLeavesInMemory(options.filter ?? options.where, (table) => tables[table]); - const hits = rows.filter((r) => matches(r, where)); + const hits = rows.filter((r) => matches(r, options.filter ?? options.where)); return typeof options.limit === 'number' ? hits.slice(0, options.limit) : hits; }, async findOne(object: string, options: any = {}) { @@ -253,7 +250,16 @@ async function makeStack( reached = true; // A write stops at the engine's door: reaching it is the admission // under test, and no write verb is exercised on this double. - if (operation === 'read') rows = await engine.find(OBJECT, { where: opCtx.ast.where }); + // [ADR-0155 plan step 6] The share-grant leaf in the scoped `where` + // is resolved here, once for the statement, as a driver's + // semi-join is (`shared-record-ids-in-memory.testkit.ts`): this + // double is no driver. With the share store down, the statement + // fails on that fault, whichever arm the row would match. + if (operation === 'read') { + rows = await engine.find(OBJECT, { + where: resolveFixedReadLeavesInMemory(opCtx.ast.where, (table) => engine._tables[table]), + }); + } // [#20013] …except the one step the engine takes at that door // before its statement: it runs the installed stored-row seam // (`postHookWriteImageCheck`) on the row it writes, the prior row diff --git a/packages/plugins/plugin-security/src/explain-read-verdict-inputs.test.ts b/packages/plugins/plugin-security/src/explain-read-verdict-inputs.test.ts index b698f2ada3f..f03f9132b6c 100644 --- a/packages/plugins/plugin-security/src/explain-read-verdict-inputs.test.ts +++ b/packages/plugins/plugin-security/src/explain-read-verdict-inputs.test.ts @@ -162,9 +162,7 @@ function makeEngine(schema: Record) { getSchema: (name: string) => (name === OBJECT ? schema : undefined), async find(object: string, options: any = {}) { const rows = (tables[object] ??= []); - // [ADR-0155 plan step 6] The share-grant leaf, resolved once for the statement. - const where = resolveFixedReadLeavesInMemory(options.filter ?? options.where, (table) => tables[table]); - return rows.filter((r) => matches(r, where)).slice(0, options.limit ?? 1000); + return rows.filter((r) => matches(r, options.filter ?? options.where)).slice(0, options.limit ?? 1000); }, async findOne(object: string, options: any = {}) { assertEngineFindOnePredicate(object, options); @@ -263,7 +261,12 @@ async function makeStack(opts: { schema?: Record; withoutHierar let result: any[] | undefined; await securityMw(opCtx, async () => { await sharingMw(opCtx, async () => { - result = await engine.find(OBJECT, { where: opCtx.ast.where }); + // [ADR-0155 plan step 6] The share-grant leaf in the scoped `where`, + // resolved here once for the statement, as a driver's semi-join is + // (`shared-record-ids-in-memory.testkit.ts`): this double is no driver. + result = await engine.find(OBJECT, { + where: resolveFixedReadLeavesInMemory(opCtx.ast.where, (table) => engine._tables[table]), + }); }); }); if (!result) throw new Error('a middleware swallowed the find'); diff --git a/packages/plugins/plugin-security/src/shared-record-ids-in-memory.testkit.ts b/packages/plugins/plugin-security/src/shared-record-ids-in-memory.testkit.ts index e69732b99ac..49558b71e13 100644 --- a/packages/plugins/plugin-security/src/shared-record-ids-in-memory.testkit.ts +++ b/packages/plugins/plugin-security/src/shared-record-ids-in-memory.testkit.ts @@ -20,6 +20,11 @@ * a row would have matched. A leaf anywhere but an `$in` comparand is one the * engine refuses, and throws here. * + * Call it where the scoped `where` is handed to the double, never inside the + * double's own `find`: `check:objectql-double-limit` lifts a `find` double out + * of its file to drive it, and an imported call in its body cannot be driven, + * so the double reads UNJUDGED and the baseline never grows. + * * `.testkit.ts`, not `.test.ts`: it holds no assertions and is not collected * as a suite, and it is imported only by tests. */ From 60865ad7d6b6aff3d24f75ac74de3614c299d67e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 07:24:37 +0000 Subject: [PATCH 3/8] fix(plugin-sharing): the storage arm of the inert-grant verdict is asked last The R2 arm sat above the public check, so a shipped object that is both federated and public (or phantom-anchored) had its grant refusal re-attributed to the storage arm: the dogfood control that guards that order went red. It is now asked after every arm that shipped, and only lifts nothing where the public arm's external floor would otherwise admit. The sharing-rule remedy follows the same order. Pinned in share-arm-boot.test.ts with a declaring-driver control. Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz Co-authored-by: Claude --- .../plugin-sharing/src/share-arm-boot.test.ts | 21 ++++++++++++ .../plugin-sharing/src/sharing-service.ts | 33 ++++++++++--------- 2 files changed, 39 insertions(+), 15 deletions(-) diff --git a/packages/plugins/plugin-sharing/src/share-arm-boot.test.ts b/packages/plugins/plugin-sharing/src/share-arm-boot.test.ts index 3b982266c8b..e557aaba1d4 100644 --- a/packages/plugins/plugin-sharing/src/share-arm-boot.test.ts +++ b/packages/plugins/plugin-sharing/src/share-arm-boot.test.ts @@ -204,6 +204,27 @@ describe('[ADR-0155 ② ruled R2] a driver beside sys_record_share that does not expect(sharing.shareGrantsInertReason('doc')).toMatch(/stored by driver 'mongo-like', which does not evaluate a share grant/); }); + it('is asked last: a shipped refusal keeps its attribution, and on a public object the external floor lifts nothing there', () => { + const publicDoc = { name: 'doc', sharingModel: 'public_read_write', fields: { owner_id: { type: 'lookup' } } }; + const sharing = engineWith({ + getSchema: () => publicDoc, + getDriverForObject: () => ({ name: 'mongo-like', supports: {} }), + fixedReadLeafClassOf: () => null, + }); + // For every recipient: the public arm's shipped reason and remedy, not the storage arm's. + expect(sharing.sharingRuleObjectRefusal('doc')) + .toMatch(/is not under record-sharing enforcement .*give the object a private or read-only sharing model/); + // An external member, whom the owner-only floor lets a share admit (#25549): the storage arm refuses. + expect((sharing as any).inertGrantReason('doc', 'external')).toMatch(/stored by driver 'mongo-like'/); + // CONTROL: on a driver that evaluates the leaf, the floor lifts as it shipped. + const declaring = engineWith({ + getSchema: () => publicDoc, + getDriverForObject: () => ({ name: 'sql', supports: { fixedReadLeaves: ['SharedRecordIds'] } }), + fixedReadLeafClassOf: () => null, + }); + expect((declaring as any).inertGrantReason('doc', 'external')).toBeNull(); + }); + it('an engine that cannot say writes the leaf, and the seam stands behind it', () => { expect(engineWith({}).shareGrantsInertReason('doc')).toBeNull(); expect(engineWith({ getDriverForObject: () => { throw new Error('boom'); } }).shareGrantsInertReason('doc')).toBeNull(); diff --git a/packages/plugins/plugin-sharing/src/sharing-service.ts b/packages/plugins/plugin-sharing/src/sharing-service.ts index d1bf713b298..9ba121b674b 100644 --- a/packages/plugins/plugin-sharing/src/sharing-service.ts +++ b/packages/plugins/plugin-sharing/src/sharing-service.ts @@ -1863,20 +1863,14 @@ export class SharingService implements ISharingService { if (declared === 'controlled_by_parent') { return `'${object}' is controlled by its parent (master-detail); share the master record instead`; } - // [ADR-0155 ② ruled R2] ADR-0111 D7's arm for the storage rows: no gate - // consults a share row on an object whose storage cannot evaluate the share - // arm. Asked before the model and the anchor, because it holds whatever - // they are: neither a private model nor a declared remote owner column - // makes such a row count, and for the external population on a public - // model it is the one reason that applies. - const shareArm = this.shareGrantsInertReason(object); - if (shareArm) return shareArm; const isPublic = effectiveSharingModel(schema) === 'public'; if (isPublic || !hasOwnerField(schema)) { // [#25549] The external floor composes over `owner_id`, so the arm can lift // only where that column is real: present, and not a phantom anchor. if (recipient !== undefined && isPublic && hasOwnerField(schema) && !hasPhantomOwnerAnchor(schema)) { - if (recipient === 'external') return null; + // [ADR-0155 ② ruled R2] …and only where the storage evaluates the + // share arm: the floor's grant would be read through it. + if (recipient === 'external') return this.shareGrantsInertReason(object); return recipient === 'internal' ? `'${object}' has a public sharing model, so a share row on it is consulted only for an ` + `external member of the record's organization, and the recipient is not one` @@ -1932,7 +1926,12 @@ export class SharingService implements ISharingService { + `platform's injected anchor, not a remote column — the record-level gates read it off a ` + `table that does not have it, so a share row on it would never be consulted`; } - return null; + // [ADR-0155 ② ruled R2] ADR-0111 D7's arm for the storage rows: no gate + // consults a share row on an object whose storage cannot evaluate the share + // arm. Asked LAST, so every arm above keeps the attribution it shipped + // with (a new branch above the public check would re-attribute a shipped + // object's refusal); it answers only where nothing above already refuses. + return this.shareGrantsInertReason(object); } /** @@ -1983,18 +1982,22 @@ export class SharingService implements ISharingService { if (declared === 'controlled_by_parent') { return 'Author the rule on its master object instead.'; } - if (this.shareGrantsInertReason(object)) { - return `To use sharing rules on it, store '${object}' on the datasource of 'sys_record_share', on a driver ` - + 'that evaluates share grants (the SQL drivers do).'; - } // Asked before the model: a federated object whose `owner_id` is the // injected anchor already HAS that field, public or not, and a private // model would still meet the phantom-anchor refusal. if (schema && hasOwnerField(schema) && hasPhantomOwnerAnchor(schema)) { return `To use sharing rules on it, declare a real remote '${OWNER_FIELD}' column on the federated object.`; } - return `To use sharing rules on it, give the object a private or read-only sharing model ` + const modelRemedy = `To use sharing rules on it, give the object a private or read-only sharing model ` + `(sharingModel: 'private' or 'read') and an '${OWNER_FIELD}' field.`; + // [ADR-0155 ② ruled R2] In the verdict's own order: the storage arm is the + // reason only where the model and the owner column already allow sharing. + if (schema && (effectiveSharingModel(schema) === 'public' || !hasOwnerField(schema))) return modelRemedy; + if (this.shareGrantsInertReason(object)) { + return `To use sharing rules on it, store '${object}' on the datasource of 'sys_record_share', on a driver ` + + 'that evaluates share grants (the SQL drivers do).'; + } + return modelRemedy; } /** From 56a0828d3e6ba18cf13318a4de8f482484a321d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:45:43 +0000 Subject: [PATCH 4/8] test(plugin-sharing): the authored-row deferral double's matcher is back to its base text No statement in that suite hands the double a share-grant leaf (the predicate-update pin reads the scope off the AST, never through the matcher), so the leaf resolution added there was dead, and it made the matcher unliftable for check:where-matcher: naming the double's own `tables` pulled module fixtures into the lift out of order. A leaf that did reach the matcher would throw on `.includes`, loudly. Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz Co-authored-by: Claude --- .../plugin-sharing/src/authored-row-write-deferral.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/plugins/plugin-sharing/src/authored-row-write-deferral.test.ts b/packages/plugins/plugin-sharing/src/authored-row-write-deferral.test.ts index 417b722e3af..60fb56676d9 100644 --- a/packages/plugins/plugin-sharing/src/authored-row-write-deferral.test.ts +++ b/packages/plugins/plugin-sharing/src/authored-row-write-deferral.test.ts @@ -64,7 +64,6 @@ import { SharingService, type SharingSecurityProbe } from './sharing-service.js' import { buildSharingMiddleware } from './sharing-plugin.js'; import { SharedRecordIds } from '@objectstack/spec/data'; import { WRITE_ACCESS_LEVELS } from './access-level.js'; -import { inMembers } from './shared-record-ids.testkit.js'; // ── metadata ─────────────────────────────────────────────────────────────── @@ -200,8 +199,7 @@ function makeEngine() { for (const [k, v] of Object.entries(filter)) { if (k === '$or' || k === '$and') continue; if (v != null && typeof v === 'object' && '$in' in (v as any)) { - // [ADR-0155] A share-grant leaf resolves over this double's own share rows. - if (!inMembers((v as any).$in, tables.sys_record_share).includes(row[k])) return false; + if (!(v as any).$in.includes(row[k])) return false; continue; } if (row[k] !== v) return false; From 76a4bc74f2910ea1723f0c73617e2bb549eb722e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 09:30:03 +0000 Subject: [PATCH 5/8] docs(sharing): the contract, the ADR anchor and the data skill follow the share-grant leaf switch - ADR-0155: a dated note repoints the grant-read bullet's anchor from the removed grantedRecordIds to the leaf's blank-id guard (FixedInnerRead); the bullet names the symbol bare. - ISharingService prose states the share arm as the leaf, in the present tense, and that grants do not count (no share arm, grant and rule doors refuse SHARING_NOT_ENABLED) where the leaf cannot be evaluated (R2). Prose only, no type change. - The D-0 conformance comment describes the pre-switch read in the past. - objectstack-data datasources rule: one sentence on where share grants count, paid by cutting restatement in the same file (908 -> 909 tokens, ceiling 911 unchanged). - Changeset: the PostgreSQL 16 no-grant total cost, measured, and the follow-up measurement. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz --- .changeset/33787-shared-record-ids-switch.md | 2 +- ...er-to-an-engine-internal-semi-join-leaf.md | 11 +++- .../spec/src/contracts/sharing-service.ts | 55 +++++++++++-------- .../data/fixed-read-leaf-conformance.test.ts | 5 +- skills/objectstack-data/rules/datasources.md | 16 +++--- 5 files changed, 53 insertions(+), 36 deletions(-) diff --git a/.changeset/33787-shared-record-ids-switch.md b/.changeset/33787-shared-record-ids-switch.md index 2537ce23b0a..405b754a194 100644 --- a/.changeset/33787-shared-record-ids-switch.md +++ b/.changeset/33787-shared-record-ids-switch.md @@ -28,4 +28,4 @@ Metadata-protocol: none 2. Each transaction pays one savepoint and one catalog read per table it compares a leaf against, when the table has no pooled reading. 3. A failed catalog read inside that savepoint rolls back the caller's concurrent statements on the same transaction. The sharing plugin issues no statement of its own that carries the leaf, and none of its reads runs inside a caller's transaction or concurrently with another on one: its own reads are sequential system reads. -**What it costs, quoted no wider than ADR-0155 quotes it.** For the scope statements alone (an account page, its total and the two grant reads), at 1M rows and 5,000 grants, the id-list scope against the subquery scope read PostgreSQL 21.6 → 7.0 ms and SQLite 18.3 → 12.1 ms. It is not a whole-request figure. For a caller holding no grant, whose scope was the bare owner match and is now an `$or` with the subquery, SQLite still serves the page and its total from the owner index; PostgreSQL 16 serves the page as before but plans the total as a sequential scan, which grows with the table. +**What it costs, quoted no wider than ADR-0155 quotes it.** For the scope statements alone (an account page, its total and the two grant reads), at 1M rows and 5,000 grants, the id-list scope against the subquery scope read PostgreSQL 21.6 → 7.0 ms and SQLite 18.3 → 12.1 ms. It is not a whole-request figure. For a caller holding no grant, whose scope was the bare owner match and is now an `$or` with the subquery, SQLite still serves the page and its total from the owner index; PostgreSQL 16 serves the page as before but plans the total as a sequential scan, which grows with the table: measured, that caller's total went from 1.46 to 7.29 ms at 100k rows and from 7.88 to 42.21 ms at 1M, the page flat at both. SQLite keeps the owner index. Follow-up #36034 measures `id = ANY(ARRAY(SELECT …))` against the subquery for that caller on PostgreSQL. diff --git a/docs/adr/0155-sharing-scope-share-grants-lower-to-an-engine-internal-semi-join-leaf.md b/docs/adr/0155-sharing-scope-share-grants-lower-to-an-engine-internal-semi-join-leaf.md index 5ceadbc8681..5cd4fd30212 100644 --- a/docs/adr/0155-sharing-scope-share-grants-lower-to-an-engine-internal-semi-join-leaf.md +++ b/docs/adr/0155-sharing-scope-share-grants-lower-to-an-engine-internal-semi-join-leaf.md @@ -157,7 +157,7 @@ Three things were the maintainer's, put with a recommendation each, and the main organization. The security middleware passes a system context through, and `packages/objectql/src/engine-driver-options.ts#driverReadScope` projects no driver tenant scope for such a context. So the read runs outside the tenant wall, and it returns the user's rows for the object whatever - organization each row carries. `packages/plugins/plugin-sharing/src/sharing-service.ts#grantedRecordIds` drops a + organization each row carries. `grantedRecordIds` drops a nullish `record_id`, stringifies the rest and drops the empty string. - **The approval arm.** `packages/plugins/plugin-sharing/src/sharing-service.ts#pendingApproverReadGrants` asks the approvals service for the records a pending step waits on the caller for. They grant read only, none to a delegated @@ -194,6 +194,15 @@ Three things were the maintainer's, put with a recommendation each, and the main that side (a `private` model for a read; a `private` or `public_read` model for a predicate update; for an external principal, whatever the external floor leaves closed). +> **Note (2026-11-21, #33787) — `grantedRecordIds` is gone; its filter is the leaf's blank-id guard.** Plan step 6 +> removed the grant read above, and `grantedRecordIds` with it, from +> `packages/plugins/plugin-sharing/src/sharing-service.ts`: the sharing scopes carry the share arm as the +> `SharedRecordIds` leaf, and no grant is read into a list. What `grantedRecordIds` did to a grant row, dropping a +> nullish or empty `record_id`, is now the blank-id guard every evaluator owes the leaf's inner read, declared with +> `packages/spec/src/data/fixed-read-leaf.ts#FixedInnerRead` (D2's blank-id guard bullet). The grant-read bullet +> above anchored the removed symbol; it now names the symbol bare, as D2 does, and this note carries the live +> anchor. The bullet otherwise stands as written, a reading of `b8ac0e24`. + ### Why no existing form serves - **`ReadableIds` means one thing**: the ids of P this caller may read. Its SQL always projects the parent's `id` diff --git a/packages/spec/src/contracts/sharing-service.ts b/packages/spec/src/contracts/sharing-service.ts index 479ce0c4da4..724288c3ef0 100644 --- a/packages/spec/src/contracts/sharing-service.ts +++ b/packages/spec/src/contracts/sharing-service.ts @@ -58,19 +58,24 @@ * `sharing-service.test.ts` and the `exec-context-annotation.pin.ts` * files in `plugin-sharing` / `plugin-approvals`. * - * ## The read scope's share arm becomes an engine-internal leaf (ADR-0155) - * - * Today the default implementation carries the read scope's share arm as a - * list, `{ id: { $in: [granted ids] } }`, read from `sys_record_share` before - * the query runs, at most 5,000 grants per read: past that cap a member - * silently loses access, which ADR-0155 removes. From plugin-sharing's switch - * on (ADR-0155 plan step 6) the arm is a `SharedRecordIds` leaf - * (`../data/shared-record-ids.ts`): a branded value the driver compiles as a - * subquery over `sys_record_share` inside the same statement, so every grant - * counts, at any count. The predicate-update scope the default implementation - * composes carries the leaf's write form the same way (ADR-0155 ③ ruled A). - * Until that switch nothing below applies: the arm stays the list. From it on, - * three things hold for anyone who reads this contract: + * ## The read scope's share arm is an engine-internal leaf (ADR-0155) + * + * The default implementation carries the read scope's share arm as a + * `SharedRecordIds` leaf (`../data/shared-record-ids.ts`): a branded value the + * driver compiles as a subquery over `sys_record_share` inside the same + * statement, so every grant counts, at any count. The predicate-update scope + * the default implementation composes carries the leaf's write form the same + * way (ADR-0155 ③ ruled A). Before plugin-sharing's switch (ADR-0155 plan + * step 6) the arm was a list, `{ id: { $in: [granted ids] } }`, read from + * `sys_record_share` before the query ran and capped at 5,000 grants per read: + * past the cap a member silently lost access. Share grants count only where + * the leaf can be evaluated. On an object bound to another datasource than + * `sys_record_share`, or stored by a driver whose `supports.fixedReadLeaves` + * does not list the leaf, the default implementation writes no share arm and + * reads no grant row, and its grant and sharing-rule doors refuse a new grant + * there as inert, `SHARING_NOT_ENABLED` / 422 (ADR-0155 ② ruled R2, ADR-0111 + * D7); owner, queue and approval access are unchanged. Three things hold for + * anyone who reads this contract: * * - **The answer is handed to the engine in process.** ⛔ Never serialise it * and never match it with a generic in-process matcher. A copy that crossed @@ -100,9 +105,9 @@ * · A narrowing that names NO object — a middleware or a find hook * registered for no object, or for `'*'` — is not run on the share arm. * On a host where such a registration changes a system read of - * `sys_record_share`, the share arm's rows can differ from today's, and - * nothing refuses, reports or logs it: this paragraph is the telling - * (ADR-0155 D4's boundary). + * `sys_record_share`, the share arm's rows can differ from what the + * engine read returned before the switch, and nothing refuses, reports + * or logs it: this paragraph is the telling (ADR-0155 D4's boundary). * * Manual share CRUD is exposed via `grant()`, `revoke()`, and * `listShares()`. The REST layer wires these to @@ -305,13 +310,14 @@ export interface ISharingService { * principal in `context` can see for `object`. Return `null` when no * restriction applies (public object, system context, no userId). * - * [ADR-0155] From plugin-sharing's switch on, the answer's share arm is a - * `SharedRecordIds` leaf composed for `context`'s user, not a list. Hand the - * answer to an engine read in process, under `context`, a context acting on - * that user's behalf, or a system context; ⛔ never serialise it and never - * match it with a generic matcher. "The read scope's share arm becomes an engine-internal - * leaf" above says why, and what a host that registers a narrowing of reads - * of `sys_record_share` is told. + * [ADR-0155] The answer's share arm is a `SharedRecordIds` leaf composed + * for `context`'s user, not a list, and there is none on an object where + * share grants do not count (R2). Hand the answer to an engine read in + * process, under `context`, a context acting on that user's behalf, or a + * system context; ⛔ never serialise it and never match it with a generic + * matcher. "The read scope's share arm is an engine-internal leaf" above + * says why, and what a host that registers a narrowing of reads of + * `sys_record_share` is told. */ buildReadFilter( object: string, @@ -453,7 +459,8 @@ export interface ISharingService { * recipient (`VALIDATION_FAILED` — other recipient types are not enforced by * any gate and are refused rather than persisted inert, ADR-0078), and an * object in an enforcing sharing posture (`SHARING_NOT_ENABLED` — a share on - * a bypass / owner-less / `controlled_by_parent` object enforces nothing; on + * a bypass / owner-less / `controlled_by_parent` object enforces nothing, + * nor does one on an object where share grants do not count, ADR-0155 R2; on * a public object it is admitted only for a recipient who is an `external` * member of the record's organization, since that population's owner-only * floor consults it). Upserts match on `(object, record, recipient, source)` diff --git a/packages/spec/src/data/fixed-read-leaf-conformance.test.ts b/packages/spec/src/data/fixed-read-leaf-conformance.test.ts index 7c3a3ce5e87..b7b11ee0257 100644 --- a/packages/spec/src/data/fixed-read-leaf-conformance.test.ts +++ b/packages/spec/src/data/fixed-read-leaf-conformance.test.ts @@ -282,8 +282,9 @@ describe('SHARED_RECORD_IDS_CASE_SET — each wrong reading of the leaf fails th describe('SHARED_RECORD_IDS_CASE_SET — D-0, the same set as today\'s list', () => { it('the D-0 list is G read from the grant rows the way plugin-sharing reads it today, and the leaf answers its rows', () => { const grants = rowsOf(set, 'sys_record_share'); - // Today's read: one find under { object_name, recipient_type: 'user', recipient_id }, - // then grantedRecordIds — nullish ids dropped, the rest stringified, the empty string dropped. + // The read plugin-sharing made before its switch (ADR-0155 plan step 6): one find under + // { object_name, recipient_type: 'user', recipient_id }, then nullish ids dropped, the rest + // stringified, the empty string dropped. The leaf's blank-id guard (FixedInnerRead) owes the same. const today = grants .filter((g) => g.object_name === 'srid_doc' && g.recipient_type === 'user' && g.recipient_id === 'u1') .map((g) => g.record_id) diff --git a/skills/objectstack-data/rules/datasources.md b/skills/objectstack-data/rules/datasources.md index d7417b22886..86d5c962bc9 100644 --- a/skills/objectstack-data/rules/datasources.md +++ b/skills/objectstack-data/rules/datasources.md @@ -4,7 +4,9 @@ A **datasource** (`defineDatasource`, a `*.datasource.ts` file) is a connection to a data store. Objects route to one via their `datasource` field. `default` is host-reserved (connected from `OS_DATABASE_URL`; declaring one named `default` is refused). Declare one under its own name only for a -**separate** or **external** store. +**separate** or **external** store. Share grants count only on +`sys_record_share`'s datasource under a SQL driver; elsewhere a grant or +sharing rule is refused `SHARING_NOT_ENABLED` (422). ## `schemaMode` — who owns the schema @@ -16,7 +18,7 @@ named `default` is refused). Declare one under its own name only for a ## Federated (external) objects -An object on an external datasource binds to its remote table via `external`: +Each binds to its remote table via `external`: ```typescript ObjectSchema.create({ @@ -24,7 +26,7 @@ ObjectSchema.create({ datasource: 'warehouse', sharingModel: 'public_read', external: { - remoteName: 'customers', // remote TABLE (object name may differ) + remoteName: 'customers', // remote TABLE // remoteSchema: 'public', // optional schema/namespace (pg/mysql) // columnMap: { cust_region: 'region' }, // remoteColumn → localField }, @@ -33,7 +35,7 @@ ObjectSchema.create({ ``` - ❌ **`field.columnName` does not exist — on ANY object.** Authoring it is a - parse error everywhere. + parse error. - **Walled posture (`OS_TENANCY_POSTURE` `isolated`/`group`): every external object states its organization scope** — its own `organization_id` field (or `columnMap` onto it), `tenancy: { enabled: false }` (shared), or @@ -42,8 +44,7 @@ ObjectSchema.create({ ## Auto-connect (no `onEnable`) -A declared datasource is connected **automatically at boot** when it is -**meaningfully addressed**: +A declared datasource connects at boot when it is **meaningfully addressed**: 1. it is **external** (`schemaMode !== 'managed'`), **or** 2. an object **explicitly** binds via `object.datasource === `, **or** @@ -77,5 +78,4 @@ A missing store, handle, instance or automation service leaves the datasource ## Writes — double opt-in -Federation is read-only by default. To write, **both** gates must be on: -`datasource.external.allowWrites: true` **and** the object's `external.writable: true`. +To write, set `datasource.external.allowWrites: true` **and** the object's `external.writable: true`. From 53f788e776ac01562a4cb2569a67b912b7de0260 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 11:10:40 +0000 Subject: [PATCH 6/8] test(dogfood): the private object's read scope is the owner match OR-ed with the share arm The [integrity] pin matched the bare owner match. The sharing read scope is now an $or whose owner disjunct is the same match, beside the share-grant leaf, so the pin asserts that disjunct. The next assertion (Bob reads only his own row) is unchanged. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz --- .../qa/dogfood/test/authored-row-write-scope.dogfood.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/qa/dogfood/test/authored-row-write-scope.dogfood.test.ts b/packages/qa/dogfood/test/authored-row-write-scope.dogfood.test.ts index 89352758eb3..f2e52814714 100644 --- a/packages/qa/dogfood/test/authored-row-write-scope.dogfood.test.ts +++ b/packages/qa/dogfood/test/authored-row-write-scope.dogfood.test.ts @@ -284,7 +284,7 @@ describe('[#7281] checkAuthoredRowWrite answers the declaration, not the caller expect( await sharing.buildReadFilter(CLOSED, bobCtx), 'private: reads are owner-scoped, which is what removed the verdict', - ).toMatchObject({ owner_id: bobId }); + ).toMatchObject({ $or: expect.arrayContaining([{ owner_id: bobId }]) }); // And it really bites on reads: Bob cannot see Alice's row on `private`. const seen = await ql.find(CLOSED, { where: {}, context: bobCtx }); From 4f11b215c37f3e276d901369bd314735f9de627b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 15:09:59 +0000 Subject: [PATCH 7/8] fix(plugin-sharing): the share-table self-scope lands in where only; parity pins below the cap; the record and the skill line follow - sharing-plugin: the sys_record_share self-scope branch no longer mirrors its scope under the AST's filter key, as the general read merge already does not; pinned for the plain and principal-less cases. - shared-record-ids-switch: at 5,000 grants, the nested position (a composed ReadableIds scope whose parent scope is the leaf, against the same composition handed the rebuilt capped list) and the delegated position (the two leaves AND-ed against the two rebuilt lists, read and update) admit the same rows. The counts above the cap are unchanged. - ADR-0155: a second dated, append-only note that the switch landed before plan step 4, so driver-memory takes R2 until a driver declares the leaf. - objectstack-data datasources rule: the 422 is the grant and rule-save doors'; a declared sharingRules rule aborts its reconcile instead. Paid in the same file (909 -> 911 tokens, ceiling 911 unchanged). Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz --- ...er-to-an-engine-internal-semi-join-leaf.md | 12 +++++ .../src/shared-record-ids-switch.test.ts | 53 ++++++++++++++++--- .../plugin-sharing/src/sharing-plugin.ts | 4 +- .../src/sharing-service.test.ts | 3 ++ skills/objectstack-data/rules/datasources.md | 9 ++-- 5 files changed, 68 insertions(+), 13 deletions(-) diff --git a/docs/adr/0155-sharing-scope-share-grants-lower-to-an-engine-internal-semi-join-leaf.md b/docs/adr/0155-sharing-scope-share-grants-lower-to-an-engine-internal-semi-join-leaf.md index 5cd4fd30212..1db1bf7dae1 100644 --- a/docs/adr/0155-sharing-scope-share-grants-lower-to-an-engine-internal-semi-join-leaf.md +++ b/docs/adr/0155-sharing-scope-share-grants-lower-to-an-engine-internal-semi-join-leaf.md @@ -529,6 +529,18 @@ The rest of the census is ②, ruled row by row in [Q2](#q2--an-evaluator-that-c `driver-odata`, a driver this repository does not ship, an object on another datasource, the analytics read-scope compilers, the explainer's record pass, and the host class D4 recognises. +> **Note (2026-11-21, #33787) — the switch landed before plan step 4, so `driver-memory` takes R2 until a driver +> declares the leaf.** Plan step 4 (#35873, `driver-memory`'s in-process evaluation) is on hold. Ruling +> [`7045701086`](https://github.com/objectstack-ai/objectstack/issues/33787#issuecomment-7045701086) made it no +> prerequisite of plan step 6, and seat 7's call in claim amendment +> [`7060526112`](https://github.com/objectstack-ai/objectstack/issues/33787#issuecomment-7060526112) confirmed what +> `driver-memory` answers meanwhile. It declares no `fixedReadLeaves`, so from the switch on it answers as ②'s R2 row +> does: its share grants go inert, stop counting and fail closed (neither scope carries the share arm, and the edit +> gate reads no grant), and the grant door and the sharing-rule save door refuse with `SHARING_NOT_ENABLED` / 422. +> The `driver-memory` row above, Q2's closing sentence and plan step 6's "lands last" record the order the plan +> expected. They stand as written, and this note records the order that happened. Once plan step 4 lands and the +> driver declares the leaf, share grants on `driver-memory` count again, with no change to plugin-sharing. + ### D6 — What the switch must show The plugin-sharing switch is where #33787 ends. Its card carries the pins the defect card and the seat set (#33787's diff --git a/packages/plugins/plugin-sharing/src/shared-record-ids-switch.test.ts b/packages/plugins/plugin-sharing/src/shared-record-ids-switch.test.ts index 4f9724c995f..96636ae7922 100644 --- a/packages/plugins/plugin-sharing/src/shared-record-ids-switch.test.ts +++ b/packages/plugins/plugin-sharing/src/shared-record-ids-switch.test.ts @@ -94,6 +94,8 @@ for (const cell of CELLS) { let knex: any; /** The queue and approval arms are wired while this is on. */ let arms = true; + /** What the `security` service hands a composed `ReadableIds` scope for DEAL: the leaf, or today's list. */ + let parentScope: 'leaf' | 'list' = 'leaf'; let grantsSeeded = 0; let marker = 0; @@ -122,11 +124,11 @@ for (const cell of CELLS) { expect(Number(stored), 'the grants the caller holds on the object').toBe(n); } - /** The retired statement's scope: the grant rows under `limit: 5000`, merged with the approval ids. */ - async function todaysScope(verb: 'read' | 'update'): Promise> { + /** The retired statement's scope for `user`: the grant rows under `limit: 5000`, merged with the approval ids. */ + async function todaysScope(verb: 'read' | 'update', user: string = ME): Promise> { const grants = await ql.find('sys_record_share', { where: { - object_name: DEAL, recipient_type: 'user', recipient_id: ME, + object_name: DEAL, recipient_type: 'user', recipient_id: user, ...(verb === 'update' ? { access_level: { $in: [...WRITE_ACCESS_LEVELS] } } : {}), }, fields: ['record_id'], @@ -136,8 +138,8 @@ for (const cell of CELLS) { (grants as Array<{ record_id: unknown }>) .map((g) => g.record_id).filter((v) => v != null).map(String).filter((v) => v !== ''), ); - if (verb === 'read' && arms) listed.add(APPROVAL); - const disjuncts: unknown[] = [{ owner_id: ME }]; + if (verb === 'read' && arms && user === ME) listed.add(APPROVAL); + const disjuncts: unknown[] = [{ owner_id: user }]; if (arms) disjuncts.push({ owner_id: null, queue: QUEUE }); if (listed.size > 0) disjuncts.push({ id: { $in: [...listed] } }); return disjuncts.length === 1 ? (disjuncts[0] as Record) : { $or: disjuncts }; @@ -159,9 +161,9 @@ for (const cell of CELLS) { await ql.update(DEAL, { name }, { where: { name: { $ne: '__never__' } }, multi: true, context } as never); return ids(await ql.find(DEAL, { where: { name }, fields: ['id'] }, { context: SYSTEM } as never)); } - async function listUpdate(): Promise { + async function listUpdate(scope?: Record): Promise { const name = `touched_${++marker}`; - const where = { $and: [{ name: { $ne: '__never__' } }, await todaysScope('update')] }; + const where = { $and: [{ name: { $ne: '__never__' } }, scope ?? await todaysScope('update')] }; await ql.update(DEAL, { name }, { where, multi: true, context: SYSTEM } as never); return ids(await ql.find(DEAL, { where: { name }, fields: ['id'] }, { context: SYSTEM } as never)); } @@ -184,7 +186,9 @@ for (const cell of CELLS) { // here, one whose read filter for an object is the sharing scope. const services = new Map([['security', { canReadObject: async () => true, - getReadFilter: (object: string, context: unknown) => service.buildReadFilter(object, context as never), + getReadFilter: (object: string, context: unknown) => (parentScope === 'list' && object === DEAL + ? todaysScope('read') + : service.buildReadFilter(object, context as never)), explain: async () => ({ allowed: true }), }]]); await (new ObjectQLPlugin({ ql, registerProtocol: false } as never) as any).init({ @@ -255,6 +259,39 @@ for (const cell of CELLS) { expect(viaLeaf).not.toContain(shrId(5000)); }); + it('5,000 grants, nested: the leaf inside a composed ReadableIds scope admits the rows today\'s list does', async () => { + arms = true; + const where = { deal_id: { $in: ReadableIds.of(DEAL) } }; + const lineIds = async () => ids(await ql.find(LINE, { where, fields: ['id'] }, { context: asMe() } as never)); + const lineCount = () => ql.count(LINE, { where }, { context: asMe() } as never); + const viaLeaf = await lineIds(); + const countViaLeaf = await lineCount(); + parentScope = 'list'; + const listed = await Promise.resolve() + .then(async () => ({ ids: await lineIds(), count: await lineCount() })) + .finally(() => { parentScope = 'leaf'; }); + const viaList = listed.ids; + const countViaList = listed.count; + // Owned, the 5,000 granted, the queued and the approval row: one line each. + expect(viaLeaf).toHaveLength(OWNED + 5000 + 2); + expect(viaLeaf).toEqual(viaList); + expect(countViaLeaf).toBe(countViaList); + }); + + it('5,000 grants, delegated: the two leaves, AND-ed, admit and update the rows today\'s two lists do', async () => { + arms = false; + const listScope = async (verb: 'read' | 'update') => ({ $and: [await todaysScope(verb, AGENT), await todaysScope(verb, ME)] }); + const viaLeaf = await leafIds(asAgentForMe()); + const viaList = ids(await ql.find(DEAL, { where: await listScope('read'), fields: ['id'] }, { context: SYSTEM } as never)); + // The agent's 100 grants on shr_*, all within the delegator's 5,000, and its 50 on rows the delegator owns. + expect(viaLeaf).toHaveLength(150); + expect(viaLeaf).toEqual(viaList); + expect(await leafCount(asAgentForMe())).toBe(await ql.count(DEAL, { where: await listScope('read') }, { context: SYSTEM } as never)); + const touched = await leafUpdate(asAgentForMe()); + expect(touched).toHaveLength(50); + expect(touched).toEqual(await listUpdate(await listScope('update'))); + }); + it('5,001 grants: the leaf counts the 5,001st, where today\'s list stops at 5,000', async () => { arms = false; await growGrantsTo(5001); diff --git a/packages/plugins/plugin-sharing/src/sharing-plugin.ts b/packages/plugins/plugin-sharing/src/sharing-plugin.ts index 830dfebd6b7..15209e65ad7 100644 --- a/packages/plugins/plugin-sharing/src/sharing-plugin.ts +++ b/packages/plugins/plugin-sharing/src/sharing-plugin.ts @@ -1512,8 +1512,10 @@ export function buildSharingMiddleware( // platform-authored as any sharing filter. markFilterSubtreeProvenance(selfScope, 'policy'); vouchCallerWhereBeforeRewrite(ast, ctx.options); + // [ADR-0155 plan step 6] `where` only, as in the general read merge + // below: the AST's `filter` key is not walked by the executor seam + // and no driver reads it, so the scope is no longer mirrored there. ast.where = composeAnd(ast.where, selfScope); - ast.filter = composeAnd(ast.filter, selfScope); ctx.ast = ast; } return next(); diff --git a/packages/plugins/plugin-sharing/src/sharing-service.test.ts b/packages/plugins/plugin-sharing/src/sharing-service.test.ts index d7ddce54c03..3f91f9fc83e 100644 --- a/packages/plugins/plugin-sharing/src/sharing-service.test.ts +++ b/packages/plugins/plugin-sharing/src/sharing-service.test.ts @@ -1519,6 +1519,8 @@ describe('[ADR-0111 D5] sys_record_share read self-scope (middleware)', () => { expect(ctx.ast.where).toEqual({ $or: [{ recipient_id: 'mallory' }, { granted_by: 'mallory' }], }); + // [ADR-0155 plan step 6] `where` only, as on the general read path. + expect(ctx.ast.filter).toBeUndefined(); }); it('manage_sharing (and the legacy manage_platform_settings) keeps the tenant-wide list', async () => { @@ -1535,6 +1537,7 @@ describe('[ADR-0111 D5] sys_record_share read self-scope (middleware)', () => { const ctx = findCtx({}); await mw(ctx, async () => {}); expect(ctx.ast.where).toEqual({ id: '__deny_all__' }); + expect(ctx.ast.filter).toBeUndefined(); }); it('system context is untouched', async () => { diff --git a/skills/objectstack-data/rules/datasources.md b/skills/objectstack-data/rules/datasources.md index 86d5c962bc9..a1237f90a20 100644 --- a/skills/objectstack-data/rules/datasources.md +++ b/skills/objectstack-data/rules/datasources.md @@ -5,8 +5,9 @@ connection to a data store. Objects route to one via their `datasource` field. `default` is host-reserved (connected from `OS_DATABASE_URL`; declaring one named `default` is refused). Declare one under its own name only for a **separate** or **external** store. Share grants count only on -`sys_record_share`'s datasource under a SQL driver; elsewhere a grant or -sharing rule is refused `SHARING_NOT_ENABLED` (422). +`sys_record_share`'s datasource under a SQL driver; elsewhere a grant or rule +save is refused `SHARING_NOT_ENABLED` (422), and a `sharingRules` reconcile +aborts on it. ## `schemaMode` — who owns the schema @@ -14,7 +15,7 @@ sharing rule is refused `SHARING_NOT_ENABLED` (422). |:--|:--| | `managed` (default) | ObjectStack owns the schema; DDL + migrations allowed. | | `external` | A mature external DB ObjectStack does **not** own; DDL forbidden; boot mismatch **fails**. | -| `validate-only` | Like `external`, but a mismatch **warns** instead of failing boot. | +| `validate-only` | Like `external`, but a mismatch **warns**. | ## Federated (external) objects @@ -27,7 +28,7 @@ ObjectSchema.create({ sharingModel: 'public_read', external: { remoteName: 'customers', // remote TABLE - // remoteSchema: 'public', // optional schema/namespace (pg/mysql) + // remoteSchema: 'public', // schema/namespace (pg/mysql) // columnMap: { cust_region: 'region' }, // remoteColumn → localField }, fields: { id: { type: 'text' }, name: { type: 'text' }, region: { type: 'text' } }, From 4bfe46dc534ebaea879becc8879f40c5f3316da0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 16:29:22 +0000 Subject: [PATCH 8/8] docs(plugin-sharing): name the storage cause of SHARING_NOT_ENABLED; changeset names @objectstack/spec (#33787) L1-a 7065619919 R1/R2 and contract record 7065677186 nit C: the two pages that list SHARING_NOT_ENABLED causes now name the ADR-0155 R2 cause (another datasource than sys_record_share, or a driver that does not evaluate the share-grant subquery) and the remedy; the changeset adds the @objectstack/spec patch line for the published contract TSDoc. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5krBqrrgxCYgjXmfbv --- .changeset/33787-shared-record-ids-switch.md | 1 + content/docs/kernel/runtime-services/sharing-service.mdx | 2 +- content/docs/permissions/sharing-rules.mdx | 7 +++++-- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/.changeset/33787-shared-record-ids-switch.md b/.changeset/33787-shared-record-ids-switch.md index 405b754a194..f394f3109ad 100644 --- a/.changeset/33787-shared-record-ids-switch.md +++ b/.changeset/33787-shared-record-ids-switch.md @@ -1,6 +1,7 @@ --- '@objectstack/plugin-sharing': patch '@objectstack/plugin-security': patch +'@objectstack/spec': patch --- fix(plugin-sharing)!: every share grant counts; the sharing scopes carry the share-grant leaf instead of a list capped at 5,000 grants (ADR-0155 plan step 6) diff --git a/content/docs/kernel/runtime-services/sharing-service.mdx b/content/docs/kernel/runtime-services/sharing-service.mdx index 77439397728..d4a8538c494 100644 --- a/content/docs/kernel/runtime-services/sharing-service.mdx +++ b/content/docs/kernel/runtime-services/sharing-service.mdx @@ -64,7 +64,7 @@ mask AND-ed with object CRUD, not a fourth `access_level`. - `PERMISSION_DENIED` (403) — the caller does not hold `canManageShares` on the record (ADR-0111 D1). On the sharing-**rule** surface (`ISharingRuleService`, declared in the same canonical source — `listRules` / `getRule` / `defineRule` / `deleteRule` / `evaluateRule`) the same code carries a second condition: the caller holds `manage_sharing` but their session resolves **no active organization**, and an org-scoped capability with no organization has no tenant whose rules it authorizes. System contexts and platform operators (`manage_platform_settings`, or the `platform_admin` position) are unaffected — see [Rule administration](/docs/permissions/sharing-rules). - `NOT_FOUND` (404) — the record is missing **or not visible to the caller** (indistinguishable by design), or a `revoke` share id does not exist / does not belong to the `scope` record. - `CONFLICT` (409) — `revoke` on a rule-materialised share (`source != 'manual'`); the next rule reconciliation would silently re-grant it. Deactivate or edit the sharing rule instead. -- `SHARING_NOT_ENABLED` (422) — `grant` on an object the sharing gates never consult for the recipient (a public sharing model, unless the recipient is an `external` member of the record's organization, whose owner-only floor does consult it; no `owner_id` field; a bypass object, `controlled_by_parent`, or a **federated** object whose `owner_id` is the platform's injected anchor rather than a real remote column — the platform provisions no storage for a federated object, so the gates read that column off a table that has not got it and can never admit). On the sharing-**rule** surface, `defineRule` (and a `sys_sharing_rule` write through the `/data` door) answers the same code when the rule's object is one no gate consults for any recipient: the rule is refused at save instead of saved to share nothing. +- `SHARING_NOT_ENABLED` (422) — `grant` on an object the sharing gates never consult for the recipient (a public sharing model, unless the recipient is an `external` member of the record's organization, whose owner-only floor does consult it; no `owner_id` field; a bypass object, `controlled_by_parent`, or a **federated** object whose `owner_id` is the platform's injected anchor rather than a real remote column — the platform provisions no storage for a federated object, so the gates read that column off a table that has not got it and can never admit; or an object whose share grants cannot count where it is stored — it sits on another datasource than `sys_record_share`, even a SQL one, or on a driver that does not evaluate the share-grant subquery, today MongoDB, in-memory and OData (ADR-0155 R2); to share its records, store it on the datasource of `sys_record_share`, on a driver that evaluates share grants, as the SQL drivers do). On the sharing-**rule** surface, `defineRule` (and a `sys_sharing_rule` write through the `/data` door) answers the same code when the rule's object is one no gate consults for any recipient: the rule is refused at save instead of saved to share nothing. ## Enforcement is automatic — do not re-check it in a hook diff --git a/content/docs/permissions/sharing-rules.mdx b/content/docs/permissions/sharing-rules.mdx index 5d01d243c22..8c7027db9ae 100644 --- a/content/docs/permissions/sharing-rules.mdx +++ b/content/docs/permissions/sharing-rules.mdx @@ -161,8 +161,11 @@ organization, every other recipient is refused with `SHARING_NOT_ENABLED` A sharing rule on an object that no sharing gate consults for any recipient is refused when it is saved: an object with no real `owner_id` (a system object without one, such as `sys_session`, or a federated object whose `owner_id` is -the platform's injected anchor), a `controlled_by_parent` detail, or a bypass -object. It is refused with `SHARING_NOT_ENABLED` (422) and a sentence that +the platform's injected anchor), a `controlled_by_parent` detail, a bypass +object, or an object whose share grants cannot count where it is stored (it +sits on another datasource than `sys_record_share`, even a SQL one, or on a +driver that does not evaluate the share-grant subquery: today MongoDB, +in-memory and OData; ADR-0155 R2). It is refused with `SHARING_NOT_ENABLED` (422) and a sentence that names the object and how to turn record sharing on for it. This holds for Setup's form and the `/data` door as well as `POST /api/v1/sharing/rules`, and for an edit that moves a rule onto such an object. A rule saved before this check keeps its row and