Skip to content

Commit 00cff2b

Browse files
committed
test(plugin-sharing): pin the declared narrowing beside its by-id remedy with plugin-security composed, and the engine's dispatch refusal at the door
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv
1 parent 7f475b9 commit 00cff2b

3 files changed

Lines changed: 234 additions & 3 deletions

File tree

‎.changeset/33928-operator-id-write-gate.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,15 @@ fix(plugin-sharing)!: the write gate judges by id exactly the writes the engine
66

77
Clause-②: no (narrowing)
88
Metadata-protocol: none
9-
Skills-docs: none — the docs already state the rule this gate now follows for every predicate write: a predicate (`multi: true`) update or delete writes only the rows the caller may write (`content/docs/permissions/permissions-matrix.mdx`, `content/docs/permissions/rls.mdx`), and no skill teaches either shape named below.
109

1110
<!-- adr-0087: not-required (no-migration-prescription) a runtime authorization answer moves: no metadata key, accepted value or stored row changes, so `os migrate meta` has nothing to rewrite -->
1211

1312
The sharing write gate now takes its by-id or bulk branch from the engine's own dispatch decision for the write's options. A write the engine runs by id is judged by id, as before. Every other write is one the engine runs as a predicate, an `$in` or `$eq` on `id` included, and it meets the bulk write scope: it writes the rows the caller may update or delete, leaves the others as they were, and answers no error.
1413

1514
A member's multi-row delete or update of rows it owns, on a `private` or `public_read` object with an `owner_id`, now lands where it answered 403 FORBIDDEN.
1615

16+
A call the engine refuses at dispatch (for example a scalar `where.id` beside another key without `multi: true`, or a payload `id` beside a `where` predicate) now gets the engine's own refusal, the answer a system caller gets, instead of this gate's 403 first. It is refused either way and nothing is written.
17+
1718
**BREAKING** for a caller of a multi-row (`multi: true`) update or delete in one of two shapes, both of which the engine runs as a predicate and the gate now judges as one:
1819

1920
- a `where` that carries a scalar `id` beside another key;
Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The declared narrowing of the sharing write gate, with plugin-security composed in.
5+
*
6+
* Under `multi: true`, a scalar `where.id` beside another `where` key is a write
7+
* the engine runs as a predicate. The sharing write gate judges it by the bulk
8+
* write scope, as it judges every predicate write, and not by id.
9+
*
10+
* Two answers are pinned on the same row, side by side:
11+
*
12+
* - the narrowed answer: a row the caller may write only because an
13+
* application row-level policy widens the sharing scope for it is not
14+
* written by that shape, and the write answers no error;
15+
* - the remedy: the same row, addressed by id alone, is judged by id and
16+
* written.
17+
*
18+
* Real stack: an `ObjectKernel` with `ObjectQLPlugin` over better-sqlite3, the
19+
* platform permission sets plus an application writer set with a row-level
20+
* update/delete policy, `SecurityPlugin` and `SharingServicePlugin`.
21+
*/
22+
23+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
24+
import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core';
25+
import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql';
26+
import { SqlDriver } from '@objectstack/driver-sql';
27+
import { SharingServicePlugin } from '@objectstack/plugin-sharing';
28+
import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity';
29+
import { PermissionSetSchema } from '@objectstack/spec/security';
30+
import { SecurityPlugin } from './security-plugin.js';
31+
import { defaultPermissionSets } from './objects/default-permission-sets.js';
32+
33+
const ORG = 'org_opidc';
34+
const ME = 'usr_opidc_me';
35+
const OTHER = 'usr_opidc_other';
36+
/** Owner-scoped (`private` OWD with an `owner_id`): record sharing enforces on it. */
37+
const DEAL = 'qa_opidc_deal';
38+
39+
const CRUD = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } as const;
40+
/** The application's writer set: a row-level policy admits an update or delete of any `open` deal. */
41+
const WRITER = PermissionSetSchema.parse({
42+
name: 'qa_opidc_writer',
43+
objects: { [DEAL]: CRUD },
44+
rowLevelSecurity: [
45+
{ name: 'qa_opidc_open_updates', object: DEAL, operation: 'update', using: "stage == 'open'" },
46+
{ name: 'qa_opidc_open_deletes', object: DEAL, operation: 'delete', using: "stage == 'open'" },
47+
],
48+
});
49+
50+
const SYSTEM = { isSystem: true, tenantId: ORG } as const;
51+
const SYS = { context: SYSTEM } as never;
52+
const asCaller = () => ({ userId: ME, tenantId: ORG, positions: [], permissions: [WRITER.name] });
53+
54+
type Outcome = { kind: 'landed' } | { kind: 'refused'; code?: string; status?: number };
55+
const outcomeOf = (p: Promise<unknown>): Promise<Outcome> =>
56+
p.then(
57+
() => ({ kind: 'landed' as const }),
58+
(e: { code?: unknown; status?: unknown; statusCode?: unknown } | null) => {
59+
const status = e?.statusCode ?? e?.status;
60+
return {
61+
kind: 'refused' as const,
62+
code: e?.code == null ? undefined : String(e.code),
63+
status: status == null ? undefined : Number(status),
64+
};
65+
},
66+
);
67+
68+
function sqliteDriverPlugin(): Plugin {
69+
return {
70+
name: 'test.driver.sqlite',
71+
type: 'standard',
72+
version: '1.0.0',
73+
async init(ctx: PluginContext) {
74+
ctx.registerService(
75+
'driver.default',
76+
new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }),
77+
);
78+
},
79+
};
80+
}
81+
82+
function objectsPlugin(): Plugin {
83+
return {
84+
name: 'test.objects',
85+
type: 'standard',
86+
version: '1.0.0',
87+
dependencies: ['com.objectstack.engine.objectql'],
88+
async init(ctx: PluginContext) {
89+
ctx.getService<{ register(m: unknown): unknown }>('manifest').register({
90+
id: 'test.operator-id-write-gate-composed',
91+
namespace: 'qa_opidc',
92+
version: '1.0.0',
93+
type: 'plugin',
94+
name: 'Operator id write gate, composed',
95+
objects: [
96+
SysUser, SysMember, SysOrganization,
97+
{
98+
name: DEAL,
99+
label: 'Deal',
100+
sharingModel: 'private',
101+
fields: {
102+
name: { type: 'text', label: 'Name' },
103+
stage: { type: 'text', label: 'Stage' },
104+
owner_id: { type: 'lookup', reference: 'sys_user', label: 'Owner' },
105+
},
106+
},
107+
],
108+
});
109+
},
110+
};
111+
}
112+
113+
describe('sharing write gate with plugin-security: a scalar id beside another key under multi meets the bulk scope; by id alone it is judged by id', () => {
114+
let kernel: ObjectKernel;
115+
let ql: ObjectQL;
116+
117+
beforeAll(async () => {
118+
kernel = new ObjectKernel({ logger: { level: 'silent' } } as never);
119+
await kernel.use(sqliteDriverPlugin());
120+
await kernel.use(new ObjectQLPlugin());
121+
await kernel.use(objectsPlugin());
122+
await kernel.use(new SecurityPlugin({
123+
defaultPermissionSets: [...defaultPermissionSets, WRITER],
124+
fallbackPermissionSet: 'member_default',
125+
}));
126+
await kernel.use(new SharingServicePlugin({ registerShareLinkRoutes: false }));
127+
await kernel.bootstrap();
128+
ql = kernel.getService<ObjectQL>('objectql');
129+
130+
await ql.insert('sys_organization', { id: ORG, name: 'Acme', slug: 'acme' }, SYS);
131+
for (const userId of [ME, OTHER]) {
132+
await ql.insert('sys_user', { id: userId, name: userId, email: `${userId}@acme.test`, email_verified: true }, SYS);
133+
await ql.insert('sys_member', { user_id: userId, organization_id: ORG, role: 'member' }, SYS);
134+
}
135+
}, 120_000);
136+
137+
afterAll(async () => {
138+
if (kernel) await Promise.race([kernel.shutdown(), new Promise<void>((r) => setTimeout(r, 10_000))]);
139+
}, 30_000);
140+
141+
const stored = async (id: string) =>
142+
((await ql.find(DEAL, { where: { id }, context: SYSTEM } as never)) as Array<{ name?: string }>)[0] ?? null;
143+
144+
/**
145+
* Another member's `open` deal, shared to the caller for reading only. Record
146+
* sharing does not let the caller write it; the application's row-level
147+
* policy does.
148+
*/
149+
const seedPolicyAdmittedRow = async (id: string) => {
150+
await ql.insert(DEAL, { id, owner_id: OTHER, created_by: OTHER, stage: 'open', name: 'seed' }, SYS);
151+
await ql.insert('sys_record_share', {
152+
object_name: DEAL, record_id: id, recipient_type: 'user', recipient_id: ME,
153+
access_level: 'read', source: 'manual',
154+
}, SYS);
155+
expect(await ql.findOne(DEAL, { where: { id }, context: asCaller() } as never)).toMatchObject({ id });
156+
};
157+
158+
it('update: the two-key predicate answers no error and leaves the row; the same row by id alone is written', async () => {
159+
await seedPolicyAdmittedRow('u_1');
160+
161+
const narrowed = await outcomeOf(
162+
ql.update(DEAL, { name: 'by_predicate' }, { where: { id: 'u_1', stage: 'open' }, multi: true, context: asCaller() } as never),
163+
);
164+
expect(narrowed).toEqual({ kind: 'landed' });
165+
expect(await stored('u_1')).toMatchObject({ name: 'seed' });
166+
167+
const byId = await outcomeOf(ql.update(DEAL, { name: 'by_id' }, { where: { id: 'u_1' }, context: asCaller() } as never));
168+
expect(byId).toEqual({ kind: 'landed' });
169+
expect(await stored('u_1')).toMatchObject({ name: 'by_id' });
170+
});
171+
172+
it('delete: the two-key predicate answers no error and leaves the row; the same row by id alone is deleted', async () => {
173+
await seedPolicyAdmittedRow('d_1');
174+
175+
const narrowed = await outcomeOf(
176+
ql.delete(DEAL, { where: { id: 'd_1', stage: 'open' }, multi: true, context: asCaller() } as never),
177+
);
178+
expect(narrowed).toEqual({ kind: 'landed' });
179+
expect(await stored('d_1')).not.toBeNull();
180+
181+
const byId = await outcomeOf(ql.delete(DEAL, { where: { id: 'd_1' }, context: asCaller() } as never));
182+
expect(byId).toEqual({ kind: 'landed' });
183+
expect(await stored('d_1')).toBeNull();
184+
});
185+
});

‎packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts‎

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -238,18 +238,20 @@ describe('sharing write gate: a write the engine runs as a predicate meets the b
238238
expect(other?.name ?? null).not.toBe('written');
239239
});
240240

241-
it('a falsy id names no row: no error, nothing written', async () => {
241+
it('a falsy id: the answer is no error (it names no row, so nothing is written)', async () => {
242242
const { mine, theirs } = await seedLines('p2');
243243

244244
expect(await delMany({ id: '' })).toMatchObject({ kind: 'landed' });
245245
expect(await delMany({ id: 0 })).toMatchObject({ kind: 'landed' });
246246
expect(await updMany({ id: '' }, { stage: 'p2_written' })).toMatchObject({ kind: 'landed' });
247+
expect(await updMany({ id: 0 }, { stage: 'p2_written' })).toMatchObject({ kind: 'landed' });
248+
expect(await updMany({ stage: 'p2_none' }, { id: '', stage: 'p2_written' })).toMatchObject({ kind: 'landed' });
247249

248250
expect(await storedLines('p2')).toEqual([...mine, theirs].sort());
249251
for (const id of [...mine, theirs]) expect(await stageOf(id)).toBe('p2');
250252
});
251253

252-
it('an empty `$in` matches no row: no error, nothing written', async () => {
254+
it('an empty `$in`: the answer is no error (it matches no row, so nothing is written)', async () => {
253255
const { mine, theirs } = await seedLines('p3');
254256

255257
expect(await delMany({ id: { $in: [] } })).toMatchObject({ kind: 'landed' });
@@ -270,6 +272,49 @@ describe('sharing write gate: a write the engine runs as a predicate meets the b
270272
expect(await stageOf('p4_read')).toBe('p4');
271273
});
272274

275+
it('control: an `$eq` update of a row the caller owns writes it', async () => {
276+
const { mine, theirs } = await seedLines('p7');
277+
278+
expect(await updMany({ id: { $eq: mine[0] } }, { stage: 'p7_written' })).toMatchObject({ kind: 'landed' });
279+
280+
expect(await stageOf(mine[0])).toBe('p7_written');
281+
expect(await stageOf(mine[1])).toBe('p7');
282+
expect(await stageOf(theirs)).toBe('p7');
283+
});
284+
285+
it('a call the engine refuses at dispatch meets the engine refusal the system context gets, not a sharing refusal, and nothing is written', async () => {
286+
const { mine, theirs } = await seedLines('p6');
287+
const refusalOf = (p: Promise<unknown>) =>
288+
p.then(
289+
() => ({ kind: 'landed' as const }),
290+
(e: { code?: unknown; status?: unknown; message?: unknown } | null) => ({
291+
kind: 'refused' as const,
292+
code: e?.code == null ? undefined : String(e.code),
293+
status: e?.status == null ? undefined : Number(e.status),
294+
message: String(e?.message),
295+
}),
296+
);
297+
// A scalar id beside another where key, without `multi`.
298+
const del = (context: unknown) => refusalOf(ql.delete(LINE, { where: { id: theirs, stage: 'p6' }, context } as never));
299+
const upd = (context: unknown) =>
300+
refusalOf(ql.update(LINE, { stage: 'p6_written' }, { where: { id: theirs, stage: 'p6' }, context } as never));
301+
// A payload id beside a where predicate.
302+
const updPayload = (context: unknown) =>
303+
refusalOf(ql.update(LINE, { id: theirs, stage: 'p6_written' }, { where: { stage: 'p6' }, context } as never));
304+
305+
for (const call of [del, upd, updPayload]) {
306+
const asSystem = await call(SYSTEM);
307+
const asMember = await call(asCaller());
308+
expect(asSystem).toMatchObject({ kind: 'refused' });
309+
expect(asMember).toEqual(asSystem);
310+
expect(asMember).not.toMatchObject({ code: 'FORBIDDEN' });
311+
expect(asMember).not.toMatchObject({ status: 403 });
312+
}
313+
314+
expect(await storedLines('p6')).toEqual([...mine, theirs].sort());
315+
for (const id of [...mine, theirs]) expect(await stageOf(id)).toBe('p6');
316+
});
317+
273318
it('control: the system context writes every row the predicate matches', async () => {
274319
const { mine, theirs } = await seedLines('p5');
275320

0 commit comments

Comments
 (0)