Skip to content
Merged
14 changes: 14 additions & 0 deletions .changeset/33683-one-share-row-per-sharing-rule.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/plugin-sharing': patch
---

fix(plugin-sharing): two sharing rules that reach one user on one record keep one grant each, so the widest level wins and revoking one rule leaves the other

Clause-②: no
Metadata-protocol: none

A user that two sharing rules reach on the same record now ends with the most permissive access either rule grants. Before this fix the two rules shared one `sys_record_share` row: `SharingService.grant` looked a rule grant up by object, record, recipient and source, without the rule's id, and overwrote the row it found. The last rule written won whatever its level, so an `edit` rule followed by a `read` rule left the user with `read`, and a project manager who is also on the project team could not edit the project. Each rule also revokes by its own id, so the merged row belonged to whichever rule wrote last: revoking that rule removed access the other rule still granted, and revoking the other rule removed nothing.

A rule-materialised grant is now keyed by its rule id too, one row per rule and recipient. The read and write gates already take the widest level across a user's rows, so nothing on the read side changes. A manual grant, and any grant made outside the rule evaluator, keeps its one row per recipient.

No migration is needed. A row two rules already share is split by the next reconcile of the rule whose id it no longer carries: that rule writes its own row, and the user regains its access.
4 changes: 2 additions & 2 deletions content/docs/permissions/system-context.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ One of the largest consumers of the flag;
| 31 | **Sharing-rule REVOCATION is skipped on the record-`afterDelete` hook** — and on that hook only | Lose: nothing permanently — the revoke is **delivered, but deferred on the unbounded shape**. The payload belongs to another subscriber: `packages/plugins/plugin-sharing/src/record-share-cascade.ts` binds on every sharing-capable object and stashes for system writes on its own account (#5103). When the deleted ids are enumerable it revokes inline; when they are not — a predicate delete whose row set the stash could not resolve — it hands the reclaim to a queued background orphan sweep instead, so the share rows outlive the deleted records until that sweep runs, with the boot orphan sweep behind it. No surviving record loses access either way, and a restart re-runs the same sweep. This is one subscriber declining work another owns, not elevation silencing a consequence. ⚠️ **Grant MATERIALISATION no longer asks** — the `afterInsert` / `afterUpdate` skips, and the `before*` stash skip that fed them, were removed by the 2026-08-31 ruling on #13533; a system write materialises exactly as a user write does | `bindRuleHooks` |
| 32 | Sharing write verdict short-circuits to `allow` | Get: writes pass the sharing gate unconditionally | `bypassVerdict` |
| 33 | Record visibility / manage-shares checks return true | Get: no ownership or Modify-All requirement | `canManageShares`, `assertCanManageShares`, `shouldBypass` |
| 34 | `grant()` skips the enforcement + manage-shares assertions | Get: the rule evaluator can materialise through the public API. Note it is **not** a bare skip: the system branch asserts the grant is not *inert* instead (a grant on an object no verdict can consult is refused) | `grant` |
| 34 | `grant()` skips the enforcement + manage-shares assertions | Get: the rule evaluator can materialise through the public API. Note it is **not** a bare skip: the system branch asserts the grant is not *inert* instead (a grant on an object no verdict can consult is refused). The system path alone also keys the upsert on the rule's `source_id`, so two rules reaching one user on one record keep one row each; any other caller keeps one row per recipient | `grant` |
| 35 | `revoke()` deletes directly, **before** the non-manual-source guard | Get: the evaluator can revoke its own grants. Lose: the `CONFLICT` guard that warns a rule-materialised grant will be silently re-granted on the next reconcile | `revoke` (the guard it deletes in front of is in the same function) |
| 36 | `listShares()` skips the management gate | Get: full enumeration of who can see a record | `listShares` |
| 37 | `sys_record_share` reads are **not** self-scoped | Get: tenant-wide share listing without `manage_sharing` | `buildSharingMiddleware` |
Expand Down Expand Up @@ -635,7 +635,7 @@ and CI refuses one that differs from what the tree produces.
| `packages/plugins/plugin-sharing/src/sharing-service.ts#assertCanManageShares` | 1 | 33 |
| `packages/plugins/plugin-sharing/src/sharing-service.ts#bypassVerdict` | 1 | 32 |
| `packages/plugins/plugin-sharing/src/sharing-service.ts#canManageShares` | 1 | 33 |
| `packages/plugins/plugin-sharing/src/sharing-service.ts#grant` | 1 | 34 |
| `packages/plugins/plugin-sharing/src/sharing-service.ts#grant` | 2 | 34 |
| `packages/plugins/plugin-sharing/src/sharing-service.ts#listShares` | 1 | 36 |
| `packages/plugins/plugin-sharing/src/sharing-service.ts#revoke` | 1 | 35 |
| `packages/plugins/plugin-sharing/src/sharing-service.ts#shouldBypass` | 1 | 33 |
Expand Down
146 changes: 146 additions & 0 deletions packages/plugins/plugin-sharing/src/field-recipient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -946,3 +946,149 @@ describe('#15072 × #14754 — the per-grant catch and the per-record kind compo
spy.mockRestore();
});
});

// ─────────────────────────────────────────────────────────────────────────
describe('two rules reaching one user on one record keep one grant each — the widest level wins, and revoking one rule leaves the other', () => {
// The shape a real app declares: a read rule for every team member, an edit
// rule for the manager, who is always on the team — so both rules name the
// same user on the same record. And an edit rule for a position, whose holder
// may be on the team too.
const TEAM = { id: 'srule_team_read', recipient_type: 'field', recipient_id: 'team_members', access_level: 'read' };
const MANAGER = { id: 'srule_manager_edit', recipient_type: 'field', recipient_id: 'project_manager', access_level: 'edit' };
const FINANCE = { id: 'srule_finance_edit', recipient_type: 'position', recipient_id: 'finance', access_level: 'edit' };
const P = { isSystem: false, userId: 'u_p', positions: [], permissions: [] } as any;

let h: ReturnType<typeof harness>;

/**
* Seed the rules so the per-record pass applies them in `order`: the pass
* walks `listRules`, which answers in name order, so the names carry the
* order and the ids stay fixed.
*/
const seedRules = (order: Row[]) =>
h.engine.seed('sys_sharing_rule', order.map((r, i) => fieldRule({ ...r, name: `r${i}_${String(r.id).slice(6)}` })));

/** P's grants on `recordId`, one `source_id:level` entry per row. */
const grantsOfP = (recordId = 'prj_1') =>
(h.engine._tables.sys_record_share ?? [])
.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. */
const readsRecord = async (recordId = 'prj_1') => {
const filter: any = await h.sharing.buildReadFilter(OBJECT, P);
return JSON.stringify(filter).includes(`"${recordId}"`);
};

beforeEach(() => {
h = harness();
h.engine._schemas[OBJECT] = {
name: OBJECT,
sharingModel: 'private',
fields: {
id: { type: 'text' },
status: { type: 'select', options: ['draft', 'approved'] },
owner_id: { type: 'lookup', reference: 'sys_user' },
team_members: { type: 'user', multiple: true },
project_manager: { type: 'lookup', reference: 'sys_user' },
},
};
h.engine.seed(OBJECT, [
{ id: 'prj_1', status: 'approved', owner_id: 'boss', team_members: ['u_p', 'u_q'], project_manager: 'u_p' },
]);
h.engine.seed('sys_user_position', [{ id: 'up_fin', position: 'finance', user_id: 'u_p' }]);
});

it.each([
['read rule first, then edit', [TEAM, MANAGER]],
['edit rule first, then read', [MANAGER, TEAM]],
])('per-record pass, %s: one row per rule, and P may edit', async (_label, order) => {
seedRules(order);
await h.rules.evaluateAllForRecord(OBJECT, 'prj_1', SYS);

expect(grantsOfP()).toEqual(['srule_manager_edit:edit', 'srule_team_read:read']);
expect(await h.sharing.checkEdit(OBJECT, 'prj_1', P)).toBe('allow');
expect(await readsRecord()).toBe(true);
// The team member who is not the manager reads and does not edit.
const Q = { ...P, userId: 'u_q' };
expect(await h.sharing.checkEdit(OBJECT, 'prj_1', Q)).toBe('deny');
});

it.each([
['read rule first, then edit', [TEAM, MANAGER]],
['edit rule first, then read', [MANAGER, TEAM]],
])('whole-rule pass, %s: re-running the read rule never lowers the edit rule\'s grant', async (_label, order) => {
seedRules(order);
for (const rule of order) await h.rules.evaluateRule(String(rule.id), SYS);
await h.rules.evaluateRule(TEAM.id, SYS);

expect(grantsOfP()).toEqual(['srule_manager_edit:edit', 'srule_team_read:read']);
expect(await h.sharing.checkEdit(OBJECT, 'prj_1', P)).toBe('allow');
});

it.each([
['read rule first, then edit', [TEAM, MANAGER]],
['edit rule first, then read', [MANAGER, TEAM]],
])('%s: revoking the edit rule leaves P the read the team rule still grants', async (_label, order) => {
seedRules(order);
await h.rules.evaluateAllForRecord(OBJECT, 'prj_1', SYS);

expect(await h.rules.revokeRuleGrants(MANAGER.id)).toBe(1);

expect(grantsOfP()).toEqual(['srule_team_read:read']);
expect(await readsRecord()).toBe(true);
expect(await h.sharing.checkEdit(OBJECT, 'prj_1', P)).toBe('deny');
});

it.each([
['read rule first, then edit', [TEAM, MANAGER]],
['edit rule first, then read', [MANAGER, TEAM]],
])('%s: revoking the read rule leaves P the edit the manager rule still grants', async (_label, order) => {
seedRules(order);
await h.rules.evaluateAllForRecord(OBJECT, 'prj_1', SYS);

// Two rows for the team rule: P's and Q's.
expect(await h.rules.revokeRuleGrants(TEAM.id)).toBe(2);

expect(grantsOfP()).toEqual(['srule_manager_edit:edit']);
expect(await h.sharing.checkEdit(OBJECT, 'prj_1', P)).toBe('allow');
});

it.each([
['field read rule first, then position edit', [TEAM, FINANCE]],
['position edit rule first, then field read', [FINANCE, TEAM]],
])('a position rule and a field rule, %s: P edits while holding the position, and reads once it is gone', async (_label, order) => {
seedRules(order);
await h.rules.evaluateAllForRecord(OBJECT, 'prj_1', SYS);

expect(grantsOfP()).toEqual(['srule_finance_edit:edit', 'srule_team_read:read']);
expect(await h.sharing.checkEdit(OBJECT, 'prj_1', P)).toBe('allow');

// P leaves the finance position: the membership recompute's user-scoped
// pass withdraws that rule's grants for P, and only those.
h.engine._tables.sys_user_position = [];
const financeRule = (await h.rules.getRule(FINANCE.id, SYS))!;
const pass = await h.rules.reconcileRuleForUser(financeRule, 'u_p');

expect(pass).toMatchObject({ grantsRevoked: 1 });
expect(grantsOfP()).toEqual(['srule_team_read:read']);
expect(await readsRecord()).toBe(true);
expect(await h.sharing.checkEdit(OBJECT, 'prj_1', P)).toBe('deny');
});

it('a row two rules once shared is split by the next pass, not kept merged', async () => {
// What a release keyed without `source_id` left behind: one row for P, the
// read rule's id on it, the edit rule's grant overwritten.
seedRules([TEAM, MANAGER]);
h.engine.seed('sys_record_share', [{
id: 'shr_merged', object_name: OBJECT, record_id: 'prj_1', recipient_type: 'user', recipient_id: 'u_p',
access_level: 'read', source: 'rule', source_id: TEAM.id,
}]);
expect(await h.sharing.checkEdit(OBJECT, 'prj_1', P)).toBe('deny');

await h.rules.evaluateAllForRecord(OBJECT, 'prj_1', SYS);

expect(grantsOfP()).toEqual(['srule_manager_edit:edit', 'srule_team_read:read']);
expect(await h.sharing.checkEdit(OBJECT, 'prj_1', P)).toBe('allow');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -475,8 +475,10 @@ describe('[#14484] the scoped UPDATE half cannot reach a row stamped with a DIFF
// `evaluateAllRulesForObject` catches per RULE and logs). Loud beats a
// wrong count, so the behaviour stands; these pins hold the measured shape
// so the next reader does not inherit the note's reading. Reachable through
// a grant that names a record another organization's grant already holds
// (the upsert key excludes `source_id`). An organization-less record that two
// a grant that names a record another organization's grant OF THE SAME RULE
// already holds: the upsert key carries a rule grant's `source_id`, and a
// declared rule served under a wall is one projection per organization, all
// carrying the rule's name as that id. An organization-less record that two
// organizations' rules both matched was the other road in; no walled sweep
// reaches such a record any more, so each pass completes (pinned below).

Expand All @@ -489,19 +491,19 @@ describe('[#14484] the scoped UPDATE half cannot reach a row stamped with a DIFF
const { driver, sharing } = await boot('isolated');
await driver.create('sys_record_share', {
id: 'shr_org_a', object_name: OBJECT, record_id: 'deal_p1', recipient_type: 'user', recipient_id: 'u_x',
access_level: 'read', source: 'rule', source_id: 'rule_org_a', organization_id: ORG_A, created_at: '2026-01-01T00:00:00Z',
access_level: 'read', source: 'rule', source_id: 'declared_rule', organization_id: ORG_A, created_at: '2026-01-01T00:00:00Z',
} as never);

await expect(
sharing.grant(
{ object: OBJECT, recordId: 'deal_p1', recipientId: 'u_x', accessLevel: 'edit', source: 'rule', sourceId: 'rule_org_b' },
{ object: OBJECT, recordId: 'deal_p1', recipientId: 'u_x', accessLevel: 'edit', source: 'rule', sourceId: 'declared_rule' },
{ ...SYSTEM, tenantId: ORG_B } as never,
),
).rejects.toMatchObject({ code: 'RECORD_NOT_FOUND', status: 404, object: 'sys_record_share' });

const rows = await allShares(driver);
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({ id: 'shr_org_a', access_level: 'read', organization_id: ORG_A, source_id: 'rule_org_a' });
expect(rows[0]).toMatchObject({ id: 'shr_org_a', access_level: 'read', organization_id: ORG_A, source_id: 'declared_rule' });
});

it("reconcile: two organizations' rules no longer meet on an organization-less record — neither walled sweep reaches it, so the second pass completes", async () => {
Expand Down
6 changes: 3 additions & 3 deletions packages/plugins/plugin-sharing/src/sharing-rule.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1824,9 +1824,9 @@ describe('#8710 — a deactivated position confers no sharing-rule shares', () =

await rules.evaluateAllForRecord('opportunity', 'opp1', SYS);
expect(ledgerReads).toBe(1);
// One share row, not two: `grant` upserts per (record, recipient), so the
// second rule re-grants the row the first one created.
expect(shareRecipients()).toEqual(['u_cfo']);
// One share row PER RULE: `grant` upserts per (record, recipient, rule),
// so the second rule writes its own row beside the first one's.
expect(shareRecipients()).toEqual(['u_cfo', 'u_cfo']);

switchCfo(false);
await rules.evaluateAllForRecord('opportunity', 'opp1', SYS);
Expand Down
48 changes: 48 additions & 0 deletions packages/plugins/plugin-sharing/src/sharing-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1358,6 +1358,54 @@ describe('[ADR-0111 D7] no inert grants', () => {
const rule = engine._tables.sys_record_share.find(r => r.id === 'shr_rule');
expect(rule?.source).toBe('rule'); // untouched
});

it('a second rule reaching the same user writes its own row; the first rule\'s row keeps its level and id', async () => {
engine._tables.sys_record_share = [{
id: 'shr_rule', object_name: 'account', record_id: 'a1',
recipient_type: 'user', recipient_id: 'bob', access_level: 'edit',
source: 'rule', source_id: 'srule_1',
}];
const second = await svc.grant(
{ object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'read', source: 'rule', sourceId: 'srule_2' } as any,
{ isSystem: true } as any,
);
expect(second.id).not.toBe('shr_rule');
const rows = engine._tables.sys_record_share.map(r => `${r.source_id}:${r.access_level}`).sort();
expect(rows).toEqual(['srule_1:edit', 'srule_2:read']);

// The same rule granting again upserts its own row, never the other's.
await svc.grant(
{ object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'edit', source: 'rule', sourceId: 'srule_2' } as any,
{ isSystem: true } as any,
);
expect(engine._tables.sys_record_share.map(r => `${r.source_id}:${r.access_level}`).sort())
.toEqual(['srule_1:edit', 'srule_2:edit']);
});

it('a manual grant keeps one row per recipient whatever `sourceId` the caller sends', async () => {
const a = await svc.grant({ object: 'account', recordId: 'a1', recipientId: 'bob', sourceId: 'x' } as any, { userId: 'alice' });
const b = await svc.grant(
{ object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'edit', sourceId: 'y' } as any,
{ userId: 'alice' },
);
expect(engine._tables.sys_record_share.length).toBe(1);
expect(b.id).toBe(a.id);
expect(b.access_level).toBe('edit');
});

it('a direct (non-system) grant keeps one row per recipient whatever non-manual `source` and `sourceId` it sends', async () => {
const a = await svc.grant(
{ object: 'account', recordId: 'a1', recipientId: 'bob', source: 'rule', sourceId: 'srule_x' } as any,
{ userId: 'alice' },
);
const b = await svc.grant(
{ object: 'account', recordId: 'a1', recipientId: 'bob', accessLevel: 'edit', source: 'rule', sourceId: 'srule_y' } as any,
{ userId: 'alice' },
);
expect(engine._tables.sys_record_share.length).toBe(1);
expect(b.id).toBe(a.id);
expect(b.access_level).toBe('edit');
});
});

describe('[ADR-0111 D5] sys_record_share read self-scope (middleware)', () => {
Expand Down
Loading
Loading