Skip to content
Merged
32 changes: 32 additions & 0 deletions .changeset/33787-shared-record-ids-switch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
'@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)

Clause-②: yes (narrowing)
Metadata-protocol: none

<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no stored row, registry key or authored value changes. What moves is how the sharing scopes count share grants (every grant, through a subquery, where a read of at most 5,000 used to stand), that grants stop counting on objects whose storage cannot evaluate that subquery, and that a host registering a narrowing of sys_record_share reads by name no longer boots. There is nothing for a migration to rewrite and no tombstone; each host-side remedy is one line, below. -->

**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: 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.
2 changes: 1 addition & 1 deletion content/docs/kernel/runtime-services/sharing-service.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 5 additions & 2 deletions content/docs/permissions/sharing-rules.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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`
Expand Down Expand Up @@ -520,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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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`]);
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
});
Expand Down Expand Up @@ -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
Expand All @@ -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 () => {
Expand Down Expand Up @@ -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 () => {
Expand Down
Loading
Loading