Skip to content

Commit ee874b1

Browse files
fix(plugin-sharing)!: a sharing rule on an object without record sharing is refused at save (#30953)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DRnRx2ArvvnWA8tEzVDhwya)_ domain:server#4 · os-elon-musk · session_016WV4cyFB75QwwCDu3S5GNZ Fixes #30621 Clause-②: no (narrowing) Metadata-protocol: none ## 维护者速读 - **改了什么**:在没有记录共享的对象上(如 `sys_session`、`sys_account`、`sys_api_key`)保存共享规则,现在两个保存入口(Setup 表单走的 `/data` 门,和 `POST /api/v1/sharing/rules`)都会拒绝,答 `422 SHARING_NOT_ENABLED`,句子点名对象并说明怎样为它开启记录共享;改对象的编辑同样拒绝。 - **为什么改**:以前这样的规则保存成功(`201`)、在 Setup 里显示为启用,但调和时每条授权都被拒、一条 `sys_record_share` 也不写,管理员以为生效了,其实什么都没共享。 - **风险与回滚**:收窄(BREAKING 横幅已加):以前能存的这类规则现在存不进。判定复用调和本身的 D7 惰性判定,两边不会不一致;有属主列的公开对象仍允许(外部成员仍能拿到授权)。已存的旧规则不迁移、不删除,仍可关闭。回滚即 revert。 - **先看**:① `packages/plugins/plugin-sharing/src/sharing-service.ts` 的 `sharingRuleObjectRefusal`(判定与 `assertNotInertGrant` 同源);② `rule-hooks.ts` 的 `bindRuleObjectEnforcementGuard`(更新只在换对象时检查);③ `sharing-rule-service.ts` 的 `defineRule` 新增检查。 - **两分钟验证**:`pnpm --filter @objectstack/plugin-sharing exec vitest run src/sharing-rule-object-enforcement.test.ts`,预期 9 个测试全绿。 - **需要你做的**:无。你已在席位线程的决策卡上点头(破坏性),由席位落地。 ## What changes Before, an administrator could save a sharing rule (`sys_sharing_rule`) on an object no sharing gate consults. The save answered `201`, the rule showed as active in Setup, and its reconcile then met the ADR-0111 D7 inert-grant guard (`SharingService.assertNotInertGrant`, `SHARING_NOT_ENABLED`) and wrote no `sys_record_share`, so the recipients saw nothing more than before. Now both save doors refuse such a rule and save nothing: 1. **The verdict, from one place.** `SharingService.sharingRuleObjectRefusal(object)` returns the refusal sentence, or `null`. It reads the same caller-independent verdict the grant pre-flight throws on (the new private `objectInertReason`, which `assertNotInertGrant` now calls too), so the save door and the reconcile cannot disagree about which objects are under enforcement. The sentence names the object, gives the D7 reason, and adds the remedy for that arm: a private or read-only `sharingModel` plus an `owner_id` field; the master object for a `controlled_by_parent` detail; a real remote `owner_id` for a federated phantom-anchor object; or "cannot be turned on" for a bypass-listed platform object. A public object that has an owner column stays admitted, because the grant service there still grants an external member of the record's organization (#25549). 2. **The `/data` door** (Setup's New and edit forms, scripts, imports): `bindRuleObjectEnforcementGuard` binds `beforeInsert` / `beforeUpdate` on `sys_sharing_rule`, bound in `sharing-plugin.ts` beside the criteria guard. An insert is checked; an update only when it moves the rule onto another object (`object_name` supplied and different from `ctx.previous`), so an administrator can still switch off a rule saved before this change. System writes pass, as with the declared-name guard. 3. **`POST /api/v1/sharing/rules`** (`SharingRuleService.defineRule`): the same check for non-system callers, before the insert or upsert; an upsert that keeps a stored rule on its object is not a move. The refusal is `SharingRuleObjectNotEnforcedError` (`rule-criteria.ts`) with `code: 'SHARING_NOT_ENABLED'` and `status: 422`: an existing code in the `@objectstack/plugin-sharing` ledger row, and the pair the per-record share routes and `POST .../evaluate` already answer for the same verdict. No new code, no `packages/spec` change. Both doors answer a declared `code` + `status` at its own status, the same mechanism `DeclaredSharingRuleNameConflictError` (409) uses on these doors. Docs: `content/docs/permissions/sharing-rules.mdx` and `content/docs/kernel/runtime-services/sharing-service.mdx` say the rule is refused at save. One changeset, `@objectstack/plugin-sharing: patch`, with the BREAKING banner and one ADR-0087 marker. ## Tests `packages/plugins/plugin-sharing/src/sharing-rule-object-enforcement.test.ts`, real `ObjectQL` + `SqlDriver` (better-sqlite3 `:memory:`), so the hook runs on the engine's own write path: - `/data` door: an insert on an owner-less object (the `sys_session` shape) is refused with `SHARING_NOT_ENABLED` / `422`, the sentence names the object, `sharingModel` and `owner_id`, and nothing is saved; CONTROL: an insert on an enforced object saves; CONTROL: a public object with an owner column is admitted; an update that moves a rule onto a non-enforced object is refused and the row keeps its object; an update that leaves a legacy rule on its object passes. - `defineRule`: a rule on an owner-less object is refused (`code` + `status`) and nothing is saved; CONTROL: a rule on an enforced object saves; an upsert that moves an existing rule onto a non-enforced object is refused. - Federated remedy (contract review should-fix, dc804fb): a `public_read_write` federated object (`external: { remoteName }`) whose `owner_id` is the registry's injected anchor is refused at the `/data` door with `422 SHARING_NOT_ENABLED`, nothing is saved, and the sentence says to declare a real remote `owner_id` column, not the `sharingModel: 'private'` remedy. Before the fix: `1 failed | 8 passed (9)`; after: `9 passed (9)`. <details><summary>Readings (final head dc804fb: plugin-sharing `Test Files 68 passed`, `Tests 1445 passed`, typecheck exit 0, derived gates 96/96 exit 0 with `--ran` 0 NOT-MEASURED; full dogfood not re-run, as the delta is one remedy sentence, its pin and docs. Earlier readings below are on head 6a24dc2; the code is unchanged since 1390d36, the last commit is the census row on a docs page)</summary> - New pins, before the fix: `Tests 8 failed (8)` (`bindRuleObjectEnforcementGuard is not a function`). After: `Tests 8 passed (8)`, lock `VERDICT command-exit 0`. - Ablation on the committed fix, through `scripts/ablation-replace.mjs` (`if (!reason) return null;` → `if (reason || !reason) return null;` in `sharingRuleObjectRefusal`): `Tests 4 failed | 4 passed (8)`. The 4 red are exactly the 4 refusal pins; the 4 controls stay green. Restore proven: blob after restore == HEAD blob `2afbcaad0cda`, `git diff HEAD` empty. The suite imports `src/` by relative path, so no dist rebuild is on the path. - `@objectstack/plugin-sharing` `pnpm test`: `Test Files 68 passed (68)`, `Tests 1444 passed (1444)`; `pnpm typecheck` (incl. `check:test-typecheck`) exit 0. One lock run, `VERDICT command-exit 0`. - Full dogfood (`pnpm --filter @objectstack/dogfood test`, no shard, after a whole-tree `turbo run build --concurrency=2`, 119/119 tasks): `Test Files 425 passed | 3 skipped (428)`, `Tests 3543 passed | 41 skipped (3584)`, `VERDICT command-exit 0`. Measured on 1390d36; 6a24dc2 adds only the census row in `content/docs/permissions/system-context.mdx`. </details> ## Acceptance notes - **Measured, not assumed: which objects are refused.** Registering every object `@objectstack/platform-objects` exports into an `ObjectQL` registry and asking `sharingRuleObjectRefusal`: 58 of 58 are refused, among them `sys_session`, `sys_account` and `sys_api_key` (no `owner_id`, no declared model), the three the card names. A custom object with an `owner_id` and a private model is admitted (the CONTROL pins). - **Error code and status: existing.** `SHARING_NOT_ENABLED` is already in the `@objectstack/plugin-sharing` row of `ERROR_CODE_LEDGER`; 422 is its published status on the share routes and `POST .../evaluate`. A scratch probe (not committed) of `@objectstack/rest`'s `mapDataError` and `classifiedRefusalAnswer` with this error answered `422` / `SHARING_NOT_ENABLED` with the sentence as `error` on both the `/data` door and the sharing-rule routes. - **Stored rules on non-enforced objects in the fixtures: 0.** The upgrade-harness fixtures hold one `sys_sharing_rule` row (`fixture-18.0`, `fixture-18.0.0`: `upgrade_harness_red_projects` on `showcase_project`, enforced; `fixture-18.0.0-next.5`: none). Declared `sharingRules` are not stored rows and are already held by `validate-sharing-rule-enforceability`'s anchor findings. Stored rules are not migrated; one already saved keeps sharing nothing and can still be switched off. - **Same predicate as the reconcile.** The save doors refuse exactly when `assertNotInertGrant` would throw: the private `objectInertReason` is now the one reading both call. A public object with an owner column is admitted on purpose (#25549, external recipients still receive grants). An object the engine has no schema for is admitted, as the grant pre-flight's inertness half admits it. - **System writes pass**, mirroring `bindDeclaredRuleNameGuard`: the platform's own writers (the ownership ceremony, migrations) and the existing system-caller pins (`system-caller-inert-grant.test.ts`, which defines such rules to pin the reconcile refusal) are unchanged. The system-context census row 40 now names `bindRuleObjectEnforcementGuard` and `defineRule` (register regenerated with `--write`). - **Not in this PR:** #30209 row 5 (the object picker still lists every object); this refusal is that card's option C on the save side only. ## Verification <details><summary>Derived gates (head 6a24dc2)</summary> - `node scripts/pm/dispatch-gates.mjs --commands`: 96 families over 10 changed paths. All 96 ran on 6a24dc2, each `:: exit 0`. - `node scripts/pm/dispatch-gates.mjs --ran FILE`: `✓ dispatch-gates --ran: 96 derived famil(ies) accounted for — 96 run, 0 NOT-MEASURED`. - First pass on 1390d36: 95 green, `pnpm check:system-context-census` red (`[read-without-a-row]` for `bindRuleObjectEnforcementGuard` and `defineRule`); fixed in 6a24dc2 by keying row 40, then `--write`; re-run green. - Families CI runs beyond the derivation (lint farm, `Test Core`, type-check lanes) are CI's; this PR cites them from its check-runs. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_016WV4cyFB75QwwCDu3S5GNZ <!-- signed: domain:server#4 · os-elon-musk · session_016WV4czvZykUqhYxYXSSDt4 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c77dd17 commit ee874b1

10 files changed

Lines changed: 409 additions & 11 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@objectstack/plugin-sharing': patch
3+
---
4+
5+
fix(plugin-sharing)!: a sharing rule on an object without record sharing is refused at save, not saved to do nothing
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped. What moves is the save door's answer to a sys_sharing_rule row whose object no sharing gate consults; a rule already stored keeps its row and can still be switched off, so there is nothing for a migration to rewrite. -->
11+
12+
**BREAKING** accept-set narrowing at the sharing-rule save doors (`@objectstack/plugin-sharing`): a rule whose object is not under record-sharing enforcement is refused with `422 SHARING_NOT_ENABLED` instead of saved.
13+
14+
- **Before.** An administrator could save a sharing rule on an object no sharing gate consults, such as `sys_session`, `sys_account` or `sys_api_key` (a system object with no `owner_id`), a public object without an owner, a `controlled_by_parent` detail or a bypass-listed object. The save answered `201`, the rule showed as active in Setup, and its reconcile then refused every grant (`SHARING_NOT_ENABLED`) and wrote no `sys_record_share`, so the rule's recipients saw nothing more than before. Nothing told the administrator.
15+
- **Now.** Both save doors refuse that rule and save nothing: the `/data` door (Setup's New and edit forms, scripts, imports) through a `sys_sharing_rule` hook guard, and `POST /api/v1/sharing/rules` (`SharingRuleService.defineRule`). The answer is `422 SHARING_NOT_ENABLED`, the pair the per-record share routes and `POST /api/v1/sharing/rules/:idOrName/evaluate` already answer for the same verdict. Its sentence names the object and says how to make it one a rule applies to, for example "give the object a private or read-only sharing model (`sharingModel: 'private'` or `'read'`) and an `owner_id` field", or "author the rule on its master object instead". An update is refused when it moves a rule onto such an object.
16+
17+
The verdict is the reconcile's own: the save doors read the same ADR-0111 D7 inert-grant check (`SharingService.sharingRuleObjectRefusal`, over `inertGrantReason`) that the grant pre-flight throws on, so the two cannot disagree. A public object that has an owner column is still admitted, because the grant service there still grants an external member of the record's organization (#25549). System writes pass, as with the declared-name guard.
18+
19+
To fix a rejected save, author the rule on an object that uses record sharing, or turn record sharing on for the object as the sentence says. A rule already stored on such an object is not migrated or deleted: it keeps sharing nothing, and an edit that leaves it on its object (for example switching it off) still saves.

‎content/docs/kernel/runtime-services/sharing-service.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ mask AND-ed with object CRUD, not a fourth `access_level`.
6060
- `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).
6161
- `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.
6262
- `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.
63-
- `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).
63+
- `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.
6464

6565
## Enforcement is automatic — do not re-check it in a hook
6666

‎content/docs/permissions/sharing-rules.mdx‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,12 +137,22 @@ the rows it owns and the rows granted to it:
137137
the object (for example `supplier in current_user.<key>`). Such a policy
138138
lifts the owner-only floor for that object, and the policy bounds the rows.
139139

140-
On a `public_read_write` object, or a system object with no `sharingModel`, a
141-
share or sharing rule takes effect for external recipients only: the grant is
142-
accepted for a recipient who is an `external` member of the record's
140+
On a `public_read_write` object, or a system object with no `sharingModel`,
141+
whose `owner_id` is real, a share or sharing rule takes effect for external
142+
recipients only: the grant is accepted for a recipient who is an `external` member of the record's
143143
organization, every other recipient is refused with `SHARING_NOT_ENABLED`
144144
(422), and a rule's evaluation writes rows for its external recipients alone.
145145

146+
A sharing rule on an object that no sharing gate consults for any recipient is
147+
refused when it is saved: an object with no real `owner_id` (a system object
148+
without one, such as `sys_session`, or a federated object whose `owner_id` is
149+
the platform's injected anchor), a `controlled_by_parent` detail, or a bypass
150+
object. It is refused with `SHARING_NOT_ENABLED` (422) and a sentence that
151+
names the object and how to turn record sharing on for it. This holds for Setup's form and the
152+
`/data` door as well as `POST /api/v1/sharing/rules`, and for an edit that moves
153+
a rule onto such an object. A rule saved before this check keeps its row and
154+
can still be switched off.
155+
146156
`externalSharingModel`, the external dial ADR-0090 D11 declared, was removed
147157
in `@objectstack/spec` 18 (ADR-0049 enforce-or-remove): while it existed no
148158
request resolved an external principal, so the value changed no answer. The schema

‎content/docs/permissions/system-context.mdx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ One of the largest consumers of the flag;
170170
| 37 | `sys_record_share` reads are **not** self-scoped | Get: tenant-wide share listing without `manage_sharing` | `buildSharingMiddleware` |
171171
| 38 | Share-link policy `enabled` check bypassed; system callers re-enter under a system context | Get: link **creation** while the policy is off — resolution is **not** bypassed since #14033 (`publicSharing.enabled` is a standing policy held at every redemption): a link minted this way does not resolve until the block is enabled | `createLink`, `revokeLink`, `listLinks` |
172172
| 39 | Sharing-rule provenance stamp skipped | Lose: the row is not marked as an admin customization — seeder / `defineRule` / boot reconcilers are "the package door" | `bindRuleProvenanceStamp` |
173-
| 40 | Sharing-rule service write + delete paths return early | Lose: the manage-rules gate on the service surface and the declared-name guard on `sys_sharing_rule` writes (a new row or a rename taking a declared rule's name, 409) — `defineRule` makes that check itself before its own system write, and the other system writers are the platform's machinery (the ownership ceremony, migrations) | `assertCanManageRules`, `bindDeclaredRuleNameGuard` |
173+
| 40 | Sharing-rule service write + delete paths return early | Lose: the manage-rules gate on the service surface and the declared-name guard on `sys_sharing_rule` writes (a new row or a rename taking a declared rule's name, 409) — `defineRule` makes that check itself before its own system write, and the other system writers are the platform's machinery (the ownership ceremony, migrations); and the object-enforcement guard on the same writes (a rule whose object is not under record-sharing enforcement, 422 `SHARING_NOT_ENABLED`), which `defineRule` likewise makes for its non-system callers | `assertCanManageRules`, `bindDeclaredRuleNameGuard`, `bindRuleObjectEnforcementGuard`, `defineRule` |
174174

175175
### 4. Approvals, attachments, comments, knowledge
176176

@@ -601,13 +601,15 @@ and CI refuses one that differs from what the tree produces.
601601
| `packages/plugins/plugin-security/src/suggested-audience-bindings.ts#assertDeploymentAuthority` | 1 | 58 |
602602
| `packages/plugins/plugin-security/src/system-write-guard.ts#isUserContextWrite` | 1 | 25 |
603603
| `packages/plugins/plugin-sharing/src/rule-hooks.ts#bindRuleHooks` | 1 | 31 |
604+
| `packages/plugins/plugin-sharing/src/rule-hooks.ts#bindRuleObjectEnforcementGuard` | 1 | 40 |
604605
| `packages/plugins/plugin-sharing/src/share-link-service.ts#createLink` | 3 | 38 |
605606
| `packages/plugins/plugin-sharing/src/share-link-service.ts#listLinks` | 1 | 38 |
606607
| `packages/plugins/plugin-sharing/src/share-link-service.ts#revokeLink` | 1 | 38 |
607608
| `packages/plugins/plugin-sharing/src/sharing-plugin.ts#buildSharingMiddleware` | 1 | 37 |
608609
| `packages/plugins/plugin-sharing/src/sharing-rule-provenance.ts#bindRuleProvenanceStamp` | 1 | 39 |
609610
| `packages/plugins/plugin-sharing/src/sharing-rule-service.ts#assertCanManageRules` | 1 | 40 |
610611
| `packages/plugins/plugin-sharing/src/sharing-rule-service.ts#bindDeclaredRuleNameGuard` | 1 | 40 |
612+
| `packages/plugins/plugin-sharing/src/sharing-rule-service.ts#defineRule` | 1 | 40 |
611613
| `packages/plugins/plugin-sharing/src/sharing-service.ts#assertCanManageShares` | 1 | 33 |
612614
| `packages/plugins/plugin-sharing/src/sharing-service.ts#bypassVerdict` | 1 | 32 |
613615
| `packages/plugins/plugin-sharing/src/sharing-service.ts#canManageShares` | 1 | 33 |

‎packages/plugins/plugin-sharing/src/rule-criteria.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,25 @@ export class SharingCriteriaValidationError extends Error {
115115
this.fields = [{ field, code: 'required', message }];
116116
}
117117
}
118+
119+
/**
120+
* [#30621] A sharing rule refused at save because its object is not under
121+
* record-sharing enforcement: the rule could never share anything.
122+
*
123+
* `code` + `status` are the declared envelope the `/data` door and the
124+
* sharing-rule routes answer at its own status: `SHARING_NOT_ENABLED` (422),
125+
* the pair the per-record share routes and `POST .../evaluate` already answer
126+
* for the same verdict. The message is `SharingService.sharingRuleObjectRefusal`'s
127+
* sentence, which names the object and how to turn record sharing on for it.
128+
*/
129+
export class SharingRuleObjectNotEnforcedError extends Error {
130+
readonly code = 'SHARING_NOT_ENABLED';
131+
readonly status = 422;
132+
/** The object the rule names. */
133+
readonly object: string;
134+
constructor(object: string, message: string) {
135+
super(message);
136+
this.name = 'SharingRuleObjectNotEnforcedError';
137+
this.object = object;
138+
}
139+
}

‎packages/plugins/plugin-sharing/src/rule-hooks.ts‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
import type { SharingRuleService } from './sharing-rule-service.js';
44
import type { SharingRuleRow } from '@objectstack/spec/contracts';
5-
import { isMatchAllCriteria, SharingCriteriaValidationError } from './rule-criteria.js';
5+
import { isMatchAllCriteria, SharingCriteriaValidationError, SharingRuleObjectNotEnforcedError } from './rule-criteria.js';
6+
import type { SharingService } from './sharing-service.js';
67
import {
78
RULE_RECOMPUTE_ROW_CAP,
89
RuleRegrantQueue,
@@ -29,6 +30,9 @@ export const RULE_REBIND_TRIGGER_PACKAGE = 'plugin-sharing:rule-rebind';
2930
*/
3031
export const RULE_CRITERIA_GUARD_PACKAGE = 'plugin-sharing:rule-criteria-guard';
3132

33+
/** Package id of {@link bindRuleObjectEnforcementGuard}'s hooks. */
34+
export const RULE_OBJECT_ENFORCEMENT_GUARD_PACKAGE = 'plugin-sharing:rule-object-enforcement-guard';
35+
3236
/*
3337
* RETIRED — the `isSystem` materialisation skip, and with it the INFO line that
3438
* announced it (`SYSTEM_WRITE_SKIP_NOTICE`, #6783 / #4707 demand 3).
@@ -355,3 +359,45 @@ export function bindRuleCriteriaGuard(engine: MinimalEngine, logger?: MinimalLog
355359
engine.registerHook('beforeUpdate', guard(false), opts);
356360
logger?.info?.('[sharing-rule] criteria guard bound on sys_sharing_rule (ADR-0049)');
357361
}
362+
363+
/**
364+
* [#30621] Refuse a `sys_sharing_rule` write whose object is not under
365+
* record-sharing enforcement.
366+
*
367+
* Before, such a rule saved (`201`) and its reconcile then met the ADR-0111 D7
368+
* inert-grant guard and wrote no `sys_record_share`: the rule sat in Setup
369+
* looking active and never applied. The verdict here is the reconcile's own
370+
* ({@link SharingService.sharingRuleObjectRefusal}), so the two cannot disagree.
371+
*
372+
* An insert is checked. An update is checked only when it MOVES the rule onto
373+
* another object (`object_name` supplied and different from the pre-image),
374+
* so an administrator can still switch off a rule saved before this guard.
375+
* System writes pass, as with the declared-name guard: `defineRule` makes the
376+
* same check itself for its non-system callers, and the remaining system
377+
* writers are the platform's own machinery.
378+
*/
379+
export function bindRuleObjectEnforcementGuard(
380+
engine: MinimalEngine,
381+
sharing: Pick<SharingService, 'sharingRuleObjectRefusal'>,
382+
): void {
383+
if (typeof engine.registerHook !== 'function') return;
384+
if (typeof engine.unregisterHooksByPackage === 'function') {
385+
engine.unregisterHooksByPackage(RULE_OBJECT_ENFORCEMENT_GUARD_PACKAGE);
386+
}
387+
const guard = (insert: boolean) => (ctx: any) => {
388+
if ((ctx?.session as any)?.isSystem) return;
389+
const data = ctx?.input?.data;
390+
if (!data || typeof data !== 'object' || Array.isArray(data)) return;
391+
const object = data.object_name;
392+
if (typeof object !== 'string' || object.length === 0) return;
393+
if (!insert) {
394+
const previous = ctx?.previous as Record<string, unknown> | undefined;
395+
if (previous && typeof previous === 'object' && previous.object_name === object) return;
396+
}
397+
const refusal = sharing.sharingRuleObjectRefusal(object);
398+
if (refusal) throw new SharingRuleObjectNotEnforcedError(object, refusal);
399+
};
400+
const opts = { object: 'sys_sharing_rule', packageId: RULE_OBJECT_ENFORCEMENT_GUARD_PACKAGE, priority: 100 };
401+
engine.registerHook('beforeInsert', guard(true), opts);
402+
engine.registerHook('beforeUpdate', guard(false), opts);
403+
}

‎packages/plugins/plugin-sharing/src/sharing-plugin.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,13 @@ import {
7373
import { SharingRuleService, bindDeclaredRuleNameGuard, bindSharingRuleActivationReconcile } from './sharing-rule-service.js';
7474
import { ShareLinkService } from './share-link-service.js';
7575
import { registerShareLinkRoutes } from './share-link-routes.js';
76-
import { bindRuleHooks, unbindAllRuleHooks, bindRuleCriteriaGuard, RULE_REBIND_TRIGGER_PACKAGE } from './rule-hooks.js';
76+
import {
77+
bindRuleHooks,
78+
unbindAllRuleHooks,
79+
bindRuleCriteriaGuard,
80+
bindRuleObjectEnforcementGuard,
81+
RULE_REBIND_TRIGGER_PACKAGE,
82+
} from './rule-hooks.js';
7783
import { bindRuleProvenanceStamp, unbindRuleProvenanceStamp } from './sharing-rule-provenance.js';
7884
import { bindPrimaryBuHooks, backfillPrimaryBu } from './primary-bu-projection.js';
7985
import { bindBusinessUnitTreeRecompute } from './bu-tree-recompute.js';
@@ -981,6 +987,10 @@ export class SharingServicePlugin implements Plugin {
981987
// match-all criteria gate has to sit on the table itself too.
982988
bindRuleCriteriaGuard(engine, ctx.logger as any);
983989

990+
// [#30621] …and so must the refusal of a rule whose object is not
991+
// under record-sharing enforcement: it would save and share nothing.
992+
if (this.service) bindRuleObjectEnforcementGuard(engine, this.service);
993+
984994
// [ADR-0131 D6 regime C] …and so must the refusal of a row, new or
985995
// renamed, that takes a declared rule's name: `defineRule` makes it
986996
// for its own callers. A declared rule is customised by a clone

0 commit comments

Comments
 (0)