Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .changeset/38254-sharing-rule-data-door-recipient.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
'@objectstack/plugin-sharing': patch
---

fix(plugin-sharing): a sharing rule saved through the `/data` door (the Setup sharing-rule form) is refused when its `user` recipient names no user the rule could share with

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

<!-- adr-0087: not-required (no-migration-prescription) a rule whose user recipient resolves to no user was already inert and is refused by defineRule; existing rows are untouched and remain editable, so there is nothing for an upgrader to migrate -->

Who sees it: an administrator saving a sharing rule in Setup, and any non-system write of `sys_sharing_rule` through the engine: `POST`/`PATCH /api/v1/data/sys_sharing_rule`, an import, a batch insert, a predicate update, or a user-context automation.

- **Before:** a rule whose `user` recipient named no user (or, on a multi-organization deployment, no member of the rule's organization) was stored. It granted no one access, and the form said it saved.
- **Now:** the insert, and an update that moves a rule onto such a recipient, answer `400 VALIDATION_FAILED` with one `fields` entry under `recipient_id`, with the sentence `POST /api/v1/sharing/rules` already answered for the same recipient. Nothing is stored. An id that does not exist and a user of another organization get the same answer. The write is judged in the organization it leaves the rule in: an `organization_id` the write supplies, else the stored rule's, else the caller's active organization (the Setup form posts none).
- An update that keeps the stored recipient is not judged, so a rule whose user has since left can still be switched off or edited. System writes are not judged.

**BREAKING** for a caller that writes a `sys_sharing_rule` row outside the system context naming a `user` recipient id that does not exist or, on a multi-organization deployment, a user outside the rule's organization: it answered 2xx and stored a rule that granted nothing; it answers 400 `VALIDATION_FAILED` and stores nothing.
The fix for a caller: send the id of an existing user, on a multi-organization deployment a member of the rule's organization.
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 @@ -105,7 +105,7 @@ mask AND-ed with object CRUD, not a fourth `access_level`.
## Typical Errors

- `FORBIDDEN` (403) — a write denied by the `canEdit` gate. Thrown by the sharing engine middleware; `canEdit` itself returns `false` rather than throwing.
- `VALIDATION_FAILED` (400) — `grant`/`revoke` called without a required field (`object`, `recordId`, `recipientId`, or `shareId`), or `grant` with a non-`user` `recipientType` (only `user` rows are enforced by the gates). The refusal names the sharing-rule recipient that delivers each declared value: `group` → `team` (a rule spells it `team` since the ADR-0090 D3 rename), `position` → `position`, `unit_and_subordinates` → `unit_and_subordinates`. A non-system `grant` is also refused when its `user` recipient names no user the gates could ever match: on a deployment walled by organization (`isolated` / `group`) with the record's organization known, the recipient must be a member of that organization, and a user of another organization gets the same answer as an id that does not exist, so the door tells no caller who exists in another tenant; on `single` it must be an existing `sys_user`. Under a wall where the grant's organization does not resolve, the recipient is not judged: the engine refuses that insert for every recipient alike (`ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED`, 500). `defineRule` refuses a non-system `user` recipient the same way, in the rule's organization, when the rule is new or its recipient changes. The rule's organization is the caller's or, for a platform operator with no active organization updating a stored rule, the stored rule's own (the engine's organization rule refuses only inserts, so that update is judged here); a new rule written with no organization under a wall is not judged, and the engine refuses its insert.
- `VALIDATION_FAILED` (400) — `grant`/`revoke` called without a required field (`object`, `recordId`, `recipientId`, or `shareId`), or `grant` with a non-`user` `recipientType` (only `user` rows are enforced by the gates). The refusal names the sharing-rule recipient that delivers each declared value: `group` → `team` (a rule spells it `team` since the ADR-0090 D3 rename), `position` → `position`, `unit_and_subordinates` → `unit_and_subordinates`. A non-system `grant` is also refused when its `user` recipient names no user the gates could ever match: on a deployment walled by organization (`isolated` / `group`) with the record's organization known, the recipient must be a member of that organization, and a user of another organization gets the same answer as an id that does not exist, so the door tells no caller who exists in another tenant; on `single` it must be an existing `sys_user`. Under a wall where the grant's organization does not resolve, the recipient is not judged: the engine refuses that insert for every recipient alike (`ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED`, 500). `defineRule` refuses a non-system `user` recipient the same way, in the rule's organization, when the rule is new or its recipient changes. The rule's organization is the caller's or, for a platform operator with no active organization updating a stored rule, the stored rule's own (the engine's organization rule refuses only inserts, so that update is judged here); a new rule written with no organization under a wall is not judged, and the engine refuses its insert. A `sys_sharing_rule` write through the `/data` door (Setup's form) gets the same refusal and sentence, judged in the organization the write leaves the rule in: an `organization_id` the write supplies, else the stored rule's, else the caller's active organization; a write that keeps the stored recipient is not judged.
- `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.
Expand Down
11 changes: 11 additions & 0 deletions content/docs/permissions/sharing-rules.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,17 @@ names the object and how to turn record sharing on for it. This holds for Setup'
a rule onto such an object. A rule saved before this check keeps its row and
can still be switched off.

A rule whose recipient is a `user` is refused when that id names no user the
rule could share with: on a multi-organization deployment, a user who is not a
member of the rule's organization; otherwise, an id no `sys_user` carries. It is
refused with `VALIDATION_FAILED` (400), and a user of another organization gets
the same answer as an id that does not exist, so the form tells no one who
exists in another tenant. Setup's form and the `/data` door answer with a
`fields` entry under `recipient_id`; `POST /api/v1/sharing/rules` answers the
same code and sentence, without `fields`. This holds for an edit that moves a
rule onto such a user as well. A rule saved before this check keeps its row and
can still be switched off.

`externalSharingModel`, the external dial ADR-0090 D11 declared, was removed
in `@objectstack/spec` 18 (ADR-0049 enforce-or-remove): while it existed no
request resolved an external principal, so the value changed no answer. The schema
Expand Down
3 changes: 2 additions & 1 deletion content/docs/permissions/system-context.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ One of the largest consumers of the flag;
| 37 | `sys_record_share` reads are **not** self-scoped | Get: tenant-wide share listing without `manage_sharing` | `buildSharingMiddleware` |
| 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` |
| 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` |
| 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` |
| 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; and the recipient guard on the same writes (a `user` recipient that names no user the rule could share with, 400 `VALIDATION_FAILED`), which `defineRule` likewise makes for its non-system callers | `assertCanManageRules`, `bindDeclaredRuleNameGuard`, `bindRuleObjectEnforcementGuard`, `bindRuleRecipientGuard`, `defineRule` |

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

Expand Down Expand Up @@ -643,6 +643,7 @@ and CI refuses one that differs from what the tree produces.
| `packages/plugins/plugin-security/src/system-write-guard.ts#isUserContextWrite` | 1 | 25 |
| `packages/plugins/plugin-sharing/src/rule-hooks.ts#bindRuleHooks` | 1 | 31 |
| `packages/plugins/plugin-sharing/src/rule-hooks.ts#bindRuleObjectEnforcementGuard` | 1 | 40 |
| `packages/plugins/plugin-sharing/src/rule-hooks.ts#bindRuleRecipientGuard` | 1 | 40 |
| `packages/plugins/plugin-sharing/src/share-link-service.ts#createLink` | 3 | 38 |
| `packages/plugins/plugin-sharing/src/share-link-service.ts#listLinks` | 1 | 38 |
| `packages/plugins/plugin-sharing/src/share-link-service.ts#revokeLink` | 1 | 38 |
Expand Down
73 changes: 73 additions & 0 deletions packages/plugins/plugin-sharing/src/rule-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { SharingRuleService } from './sharing-rule-service.js';
import type { SharingRuleRow } from '@objectstack/spec/contracts';
import { isMatchAllCriteria, SharingCriteriaValidationError, SharingRuleObjectNotEnforcedError } from './rule-criteria.js';
import type { SharingService } from './sharing-service.js';
import { validationFailure } from '@objectstack/types';
import {
RULE_RECOMPUTE_ROW_CAP,
RuleRegrantQueue,
Expand Down Expand Up @@ -33,6 +34,9 @@ export const RULE_CRITERIA_GUARD_PACKAGE = 'plugin-sharing:rule-criteria-guard';
/** Package id of {@link bindRuleObjectEnforcementGuard}'s hooks. */
export const RULE_OBJECT_ENFORCEMENT_GUARD_PACKAGE = 'plugin-sharing:rule-object-enforcement-guard';

/** Package id of {@link bindRuleRecipientGuard}'s hooks. */
export const RULE_RECIPIENT_GUARD_PACKAGE = 'plugin-sharing:rule-recipient-guard';

/*
* RETIRED — the `isSystem` materialisation skip, and with it the INFO line that
* announced it (`SYSTEM_WRITE_SKIP_NOTICE`, #6783 / #4707 demand 3).
Expand Down Expand Up @@ -427,3 +431,72 @@ export function bindRuleObjectEnforcementGuard(
engine.registerHook('beforeInsert', guard(true), opts);
engine.registerHook('beforeUpdate', guard(false), opts);
}

/**
* [#38254] Refuse a `sys_sharing_rule` write whose `user` recipient names no
* user the rule could share with.
*
* `SharingRuleService.defineRule` refuses such a recipient (#33912), but the
* Setup sharing-rule form writes through the `/data` door, a plain write on
* this table that never reaches that method. Before this guard that door
* stored the rule: it granted no one access, and the author was told it
* saved. The verdict and the sentence are `defineRule`'s own
* ({@link SharingService.userRecipientRefusal}, subject `rule`), so the two
* doors cannot disagree, and the refusal is `VALIDATION_FAILED` (400) under
* `recipient_id`.
*
* Judged in the organization the write leaves the rule in: the
* `organization_id` the write supplies (on an update, a re-point the tenant
* wall admitted), else the stored row's, else the caller's active
* organization (the one the engine stamps on a new row; the Setup form
* posts none). An id that names no
* user and a user of another organization are answered alike, so the door
* is no oracle for who exists in another tenant. With no organization under
* a wall the verdict stands aside, as it does for `defineRule`: the engine
* refuses that insert for every recipient alike.
*
* An insert with a `user` recipient is judged. An update is judged only when
* it leaves a `user` recipient that differs from the pre-image (type or id),
* so a rule whose user has since left can still be switched off or edited
* otherwise. System writes pass, as with the object guard: `defineRule`
* judges its own non-system callers, and the remaining system writers are
* the platform's own machinery.
*/
export function bindRuleRecipientGuard(
engine: MinimalEngine,
sharing: Pick<SharingService, 'userRecipientRefusal'>,
): void {
if (typeof engine.registerHook !== 'function') return;
if (typeof engine.unregisterHooksByPackage === 'function') {
engine.unregisterHooksByPackage(RULE_RECIPIENT_GUARD_PACKAGE);
}
const present = (v: unknown): string | null => (typeof v === 'string' && v.length > 0 ? v : null);
const guard = (insert: boolean) => async (ctx: any) => {
if ((ctx?.session as any)?.isSystem) return;
const data = ctx?.input?.data;
if (!data || typeof data !== 'object' || Array.isArray(data)) return;
const previous = !insert && ctx?.previous && typeof ctx.previous === 'object'
? ctx.previous as Record<string, unknown>
: undefined;
// A key present with the value `undefined` leaves the column alone (the tenant wall reads it the same way), so
// it is not a supplied value: the stored one stands and is the one judged.
const has = (key: string) => Object.prototype.hasOwnProperty.call(data, key) && data[key] !== undefined;
if (!insert && !has('recipient_type') && !has('recipient_id')) return;
const recipientType = has('recipient_type') ? data.recipient_type : previous?.recipient_type;
if (recipientType !== 'user') return;
const recipientId = present(has('recipient_id') ? data.recipient_id : previous?.recipient_id);
// A missing id is the record validator's to answer (`required`), not this guard's.
if (!recipientId) return;
if (previous && previous.recipient_type === 'user' && previous.recipient_id === recipientId) return;
const organizationId = present(data.organization_id)
?? present(previous?.organization_id)
?? present(ctx?.session?.organizationId);
const refusal = await sharing.userRecipientRefusal(recipientId, organizationId, 'rule');
if (refusal) {
throw validationFailure(refusal, [{ field: 'recipient_id', code: 'invalid_value', message: refusal }]);
}
};
const opts = { object: 'sys_sharing_rule', packageId: RULE_RECIPIENT_GUARD_PACKAGE, priority: 100 };
engine.registerHook('beforeInsert', guard(true), opts);
engine.registerHook('beforeUpdate', guard(false), opts);
}
6 changes: 6 additions & 0 deletions packages/plugins/plugin-sharing/src/sharing-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ import {
rebindRuleHooks,
bindRuleCriteriaGuard,
bindRuleObjectEnforcementGuard,
bindRuleRecipientGuard,
RULE_REBIND_TRIGGER_PACKAGE,
} from './rule-hooks.js';
import { bindRuleProvenanceStamp, unbindRuleProvenanceStamp } from './sharing-rule-provenance.js';
Expand Down Expand Up @@ -1080,6 +1081,11 @@ export class SharingServicePlugin implements Plugin {
// under record-sharing enforcement: it would save and share nothing.
if (this.service) bindRuleObjectEnforcementGuard(engine, this.service);

// [#38254] …and so must the refusal of a `user` recipient that
// names no user the rule could share with (`defineRule`'s own
// verdict, #33912): it would save and grant no one access.
if (this.service) bindRuleRecipientGuard(engine, this.service);

// [ADR-0131 D6 regime C] …and so must the refusal of a row, new or
// renamed, that takes a declared rule's name: `defineRule` makes it
// for its own callers. A declared rule is customised by a clone
Expand Down
Loading
Loading