From 3000c91b9f638f8c473d53e974274611c65d7514 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 14:35:31 +0000 Subject: [PATCH 01/13] fix(plugin-sharing): an operator-valued id is a predicate write, scoped by the bulk write filter The write gate stringified `where.id` even when it was an operator object such as `{ $in: [...] }`, and judged the row "[object Object]", so a member's multi-row delete of rows it owns was refused. Only a scalar id now names the row the by-id gate judges, the engine's own dispatch rule; any other value takes the bulk branch, where buildWriteFilter scopes the predicate. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../plugin-sharing/src/sharing-plugin.ts | 40 ++++++++++++++----- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/packages/plugins/plugin-sharing/src/sharing-plugin.ts b/packages/plugins/plugin-sharing/src/sharing-plugin.ts index e02e655a09f..2379c1a7bda 100644 --- a/packages/plugins/plugin-sharing/src/sharing-plugin.ts +++ b/packages/plugins/plugin-sharing/src/sharing-plugin.ts @@ -1773,16 +1773,38 @@ function composeAnd(existing: unknown, addition: unknown): unknown { return { $and: [existing, addition] }; } -function inferTargetId(data: any, options: any): string | number | undefined { - if (data && typeof data === 'object' && data.id != null) return data.id; +/** + * The ONE row a write addresses, or `undefined` when it addresses a predicate. + * + * Only a SCALAR id (string, number, bigint) names a row, the engine's own rule + * for picking the by-id route (`scalarDeleteId` / `scalarUpdateId` in + * `@objectstack/metadata-core`). An operator object (`{ $in: [...] }`, + * `{ $nin: [...] }`, `{ $eq: ... }`), an array or `null` in an id slot is a + * predicate over rows, which the engine dispatches to `deleteMany` / + * `updateMany` with the composed AST, so it takes the bulk branch of the write + * gate: the `buildWriteFilter` scope ANDed into that AST, the answer a bulk + * write has always had (fewer rows, no error). It is never stringified into a + * row id: `String({ $in: [...] })` is the row "[object Object]", which no + * caller owns, so every such write was refused whatever rows it named. A + * non-scalar slot does not shadow a later scalar one, as in the engine. + */ +function inferTargetId(data: any, options: any): string | number | bigint | undefined { + const slots: unknown[] = []; + if (data && typeof data === 'object') slots.push(data.id); if (options && typeof options === 'object') { - if (options.id != null) return options.id; - if (options.where && typeof options.where === 'object' && options.where.id != null) { - return options.where.id; - } - if (options.filter && typeof options.filter === 'object' && options.filter.id != null) { - return options.filter.id; - } + slots.push(options.id); + if (options.where && typeof options.where === 'object') slots.push(options.where.id); + if (options.filter && typeof options.filter === 'object') slots.push(options.filter.id); + } + for (const slot of slots) { + const id = scalarIdOf(slot); + if (id !== undefined) return id; } return undefined; } + +/** `value` when it is a scalar row id, `undefined` for an operator object, an array or anything else. */ +function scalarIdOf(value: unknown): string | number | bigint | undefined { + const t = typeof value; + return t === 'string' || t === 'number' || t === 'bigint' ? (value as string | number | bigint) : undefined; +} From 7ba0bb7755f32316a45dfc7c26da8ee12dc13439 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 14:45:55 +0000 Subject: [PATCH 02/13] test(plugin-sharing): pin the write gate's answer to an operator-valued id on a real stack Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../src/operator-id-write-gate.test.ts | 243 ++++++++++++++++++ 1 file changed, 243 insertions(+) create mode 100644 packages/plugins/plugin-sharing/src/operator-id-write-gate.test.ts diff --git a/packages/plugins/plugin-sharing/src/operator-id-write-gate.test.ts b/packages/plugins/plugin-sharing/src/operator-id-write-gate.test.ts new file mode 100644 index 00000000000..72fe7840913 --- /dev/null +++ b/packages/plugins/plugin-sharing/src/operator-id-write-gate.test.ts @@ -0,0 +1,243 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The sharing write gate on a write whose `where.id` is an OPERATOR object + * (`{ $in: [...] }`, `{ $nin: [...] }`), not a row id. + * + * The gate used to stringify any `where.id` into the row it judged by id, so + * `{ $in: ['row_1'] }` was judged as the row "[object Object]", which no caller + * owns: a member's multi-row delete of rows it owns answered 403 FORBIDDEN and + * deleted nothing. Only a scalar id names a row now (the engine's own dispatch + * rule); any other value is a predicate, and takes the bulk branch: + * `SharingService.buildWriteFilter` ANDed into the predicate. + * + * What each door answers, pinned here: + * + * - a user's bulk write over rows it owns and rows it does not keeps the + * answer every bulk write has (`buildWriteFilter`, ADR-0111 D3): fewer + * rows, no error. The rows it may not write are left as they were; + * - a cascade delete gives the answer the by-id delete of the refused child + * gives, the same refusal envelope, and deletes nothing. The gate does not + * tell a cascade from a user's bulk write: whatever shape the engine deletes + * a parent's children in, the child it may not delete refuses as by id; + * - another operator shape (`$nin`) is scoped per matched row by the same + * filter, never judged as a by-id string; + * - a scalar id is judged by id exactly as before. + * + * Real stack: an `ObjectKernel` with `ObjectQLPlugin` over better-sqlite3 and + * `SharingServicePlugin`, so every answer is the middleware the engine runs. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SharingServicePlugin } from './sharing-plugin.js'; + +const ORG = 'org_opid'; +const ME = 'usr_opid_me'; +const OTHER = 'usr_opid_other'; + +/** The parent of a cascade: open to every member, so its own delete is never the refusal. */ +const ORDER = 'qa_opid_order'; +/** Owner-scoped (`private` OWD with an `owner_id`): record sharing enforces on it. */ +const LINE = 'qa_opid_line'; + +const SYSTEM = { isSystem: true, tenantId: ORG } as const; +const SYS = { context: SYSTEM } as never; +const asCaller = () => ({ userId: ME, tenantId: ORG, positions: [] }); + +type Outcome = + | { kind: 'landed'; result: unknown } + | { kind: 'refused'; code?: string; status?: number; details?: unknown }; +const outcomeOf = (p: Promise): Promise => + p.then( + (result) => ({ kind: 'landed' as const, result }), + (e: { code?: unknown; status?: unknown; details?: unknown } | null) => ({ + kind: 'refused' as const, + code: e?.code == null ? undefined : String(e.code), + status: e?.status == null ? undefined : Number(e.status), + details: e?.details, + }), + ); + +function sqliteDriverPlugin(): Plugin { + return { + name: 'test.driver.sqlite', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService( + 'driver.default', + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + ); + }, + }; +} + +function objectsPlugin(): Plugin { + return { + name: 'test.objects', + type: 'standard', + version: '1.0.0', + dependencies: ['com.objectstack.engine.objectql'], + async init(ctx: PluginContext) { + ctx.getService<{ register(m: unknown): unknown }>('manifest').register({ + id: 'test.operator-id-write-gate', + namespace: 'qa_opid', + version: '1.0.0', + type: 'plugin', + name: 'Operator id write gate', + objects: [ + { name: ORDER, label: 'Order', sharingModel: 'public_read_write', fields: { name: { type: 'text', label: 'Name' } } }, + { + name: LINE, + label: 'Line', + sharingModel: 'private', + fields: { + name: { type: 'text', label: 'Name' }, + stage: { type: 'text', label: 'Stage' }, + owner_id: { type: 'text', label: 'Owner' }, + order: { type: 'lookup', reference: ORDER, deleteBehavior: 'cascade', label: 'Order' }, + }, + }, + ], + }); + }, + }; +} + +describe('sharing write gate: an operator-valued id is a predicate write, never the row "[object Object]"', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + + beforeAll(async () => { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as never); + await kernel.use(sqliteDriverPlugin()); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(objectsPlugin()); + await kernel.use(new SharingServicePlugin({ registerShareLinkRoutes: false })); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + }, 120_000); + + afterAll(async () => { + if (kernel) await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + }, 30_000); + + /** The line ids stored under `prefix`, as a system read sees them. */ + const storedLines = async (prefix: string) => { + const rows = (await ql.find(LINE, { context: SYSTEM } as never)) as Array<{ id: string }>; + return rows.map((r) => String(r.id)).filter((id) => id.startsWith(prefix)).sort(); + }; + /** Two lines the caller owns and one it does not, under `prefix`. */ + const seedLines = async (prefix: string, order?: string) => { + await ql.insert(LINE, [ + { id: `${prefix}_mine1`, owner_id: ME, stage: prefix, ...(order ? { order } : {}) }, + { id: `${prefix}_theirs`, owner_id: OTHER, stage: prefix, ...(order ? { order } : {}) }, + { id: `${prefix}_mine2`, owner_id: ME, stage: prefix, ...(order ? { order } : {}) }, + ], SYS); + return { mine: [`${prefix}_mine1`, `${prefix}_mine2`], theirs: `${prefix}_theirs` }; + }; + const shareToMe = (recordId: string, accessLevel: 'read' | 'edit') => + ql.insert('sys_record_share', { + object_name: LINE, record_id: recordId, recipient_type: 'user', recipient_id: ME, + access_level: accessLevel, source: 'manual', + }, SYS); + + describe('by id: unchanged', () => { + it('a scalar id the caller owns deletes; one it does not is refused 403 FORBIDDEN naming that row, and stays', async () => { + const { mine, theirs } = await seedLines('b1'); + + expect(await outcomeOf(ql.delete(LINE, { where: { id: mine[0] }, context: asCaller() } as never))) + .toMatchObject({ kind: 'landed' }); + expect(await outcomeOf(ql.delete(LINE, { where: { id: theirs }, context: asCaller() } as never))).toEqual({ + kind: 'refused', code: 'FORBIDDEN', status: 403, + details: { operation: 'delete', object: LINE, recordId: theirs }, + }); + expect(await storedLines('b1')).toEqual([mine[1], theirs].sort()); + }); + }); + + describe("a user's bulk `$in` write keeps the bulk answer (buildWriteFilter): fewer rows, no error", () => { + it('an `$in` delete naming only rows the caller owns deletes every one of them', async () => { + const { mine, theirs } = await seedLines('i1'); + + const got = await outcomeOf(ql.delete(LINE, { where: { id: { $in: mine } }, multi: true, context: asCaller() } as never)); + + expect(got).toMatchObject({ kind: 'landed' }); + expect(await storedLines('i1')).toEqual([theirs]); + }); + + it('an `$in` delete naming owned and not-owned rows deletes the owned ones, answers no error, and leaves the other', async () => { + const { mine, theirs } = await seedLines('i2'); + + const got = await outcomeOf( + ql.delete(LINE, { where: { id: { $in: [...mine, theirs] } }, multi: true, context: asCaller() } as never), + ); + + expect(got).toMatchObject({ kind: 'landed' }); + expect(await storedLines('i2')).toEqual([theirs]); + }); + + it('an `$in` update over owned, edit-shared and not-shared rows writes the rows the caller may edit, and only those', async () => { + const { mine, theirs } = await seedLines('i3'); + await ql.insert(LINE, { id: 'i3_shared', owner_id: OTHER, stage: 'i3' }, SYS); + await shareToMe('i3_shared', 'edit'); + + const got = await outcomeOf(ql.update( + LINE, { stage: 'won' }, + { where: { id: { $in: [...mine, theirs, 'i3_shared'] } }, multi: true, context: asCaller() } as never, + )); + + expect(got).toMatchObject({ kind: 'landed' }); + const rows = (await ql.find(LINE, { context: SYSTEM } as never)) as Array<{ id: string; stage: string }>; + const stages = Object.fromEntries(rows.filter((r) => r.id.startsWith('i3')).map((r) => [r.id, r.stage])); + expect(stages).toEqual({ [mine[0]]: 'won', [mine[1]]: 'won', i3_shared: 'won', [theirs]: 'i3' }); + }); + }); + + describe('another operator shape is scoped per matched row, never judged as a by-id string', () => { + it('a `$nin` delete deletes only the matched rows the caller owns, and answers no error', async () => { + const { theirs } = await seedLines('n1'); + await ql.insert(LINE, { id: 'n1_kept', owner_id: ME, stage: 'n1' }, SYS); + + const got = await outcomeOf(ql.delete( + LINE, { where: { id: { $nin: ['n1_kept'] }, stage: 'n1' }, multi: true, context: asCaller() } as never, + )); + + expect(got).toMatchObject({ kind: 'landed' }); + expect(await storedLines('n1')).toEqual(['n1_kept', theirs].sort()); + }); + }); + + describe('a cascade delete gives the answer the by-id delete of the refused child gives', () => { + it('a child the caller reads and may edit but not delete: the same refusal envelope, and nothing is deleted', async () => { + await ql.insert(ORDER, { id: 'c1', name: 'c1' }, SYS); + const { mine, theirs } = await seedLines('c1', 'c1'); + await shareToMe(theirs, 'edit'); + // The child is on the caller's read door, so the refusal is the delete gate's. + expect(await ql.findOne(LINE, { where: { id: theirs }, context: asCaller() } as never)).toMatchObject({ id: theirs }); + const own = await outcomeOf(ql.delete(LINE, { where: { id: theirs }, context: asCaller() } as never)); + expect(own).toMatchObject({ kind: 'refused', code: 'FORBIDDEN', status: 403 }); + + const got = await outcomeOf(ql.delete(ORDER, { where: { id: 'c1' }, context: asCaller() } as never)); + + expect(got).toEqual(own); + expect(await storedLines('c1')).toEqual([...mine, theirs].sort()); + expect(await ql.find(ORDER, { where: { id: 'c1' }, context: SYSTEM } as never)).toHaveLength(1); + }); + + it('a cascade over children the caller owns deletes the parent and every child', async () => { + await ql.insert(ORDER, { id: 'c2', name: 'c2' }, SYS); + await ql.insert(LINE, [ + { id: 'c2_a', owner_id: ME, order: 'c2' }, + { id: 'c2_b', owner_id: ME, order: 'c2' }, + ], SYS); + + expect(await outcomeOf(ql.delete(ORDER, { where: { id: 'c2' }, context: asCaller() } as never))) + .toMatchObject({ kind: 'landed' }); + expect(await storedLines('c2')).toEqual([]); + }); + }); +}); From e9bd87cbd37ba9c1368a78775e7c772fa9f5201a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 14:50:27 +0000 Subject: [PATCH 03/13] test(plugin-sharing): name the operator-id pin file by its card Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- ...id-write-gate.test.ts => operator-id-write-gate-33928.test.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename packages/plugins/plugin-sharing/src/{operator-id-write-gate.test.ts => operator-id-write-gate-33928.test.ts} (100%) diff --git a/packages/plugins/plugin-sharing/src/operator-id-write-gate.test.ts b/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts similarity index 100% rename from packages/plugins/plugin-sharing/src/operator-id-write-gate.test.ts rename to packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts From 4bbcebd6262ecac81675c9ae8e49e222d14bd2a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 14:51:52 +0000 Subject: [PATCH 04/13] chore(changeset): plugin-sharing patch for the operator-id write gate Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .changeset/33928-operator-id-write-gate.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 .changeset/33928-operator-id-write-gate.md diff --git a/.changeset/33928-operator-id-write-gate.md b/.changeset/33928-operator-id-write-gate.md new file mode 100644 index 00000000000..d646bbb58de --- /dev/null +++ b/.changeset/33928-operator-id-write-gate.md @@ -0,0 +1,12 @@ +--- +'@objectstack/plugin-sharing': patch +--- + +fix(plugin-sharing): a write whose `where.id` is an operator object is scoped as the predicate it is, not judged as the row "[object Object]" + +Clause-②: yes (widening): a request refused today lands when every matched row is admitted; measured again by the dev before the PR +Metadata-protocol: none + +The sharing write gate turned any `where.id` into the one row it judged by id, so `{ $in: [...] }` was judged as the row "[object Object]", which no caller owns. A member's multi-row delete or update of rows it owns, on a `private` or `public_read` object with an `owner_id`, answered 403 FORBIDDEN and wrote nothing. + +Only a scalar id (string, number, bigint) now names the row the by-id gate judges, the rule the engine already uses to pick its by-id route. Any other value in an id slot (`$in`, `$nin`, `$eq`, an array) is a predicate, and gets the answer every bulk write gets: the writable-rows filter is ANDed into it, so the write touches only the rows the caller may update or delete, and the rest are left as they were, with no error. A by-id write with a scalar id is judged exactly as before. From 665ed8be28b179b7b9a59c94cbc06b855f99ec32 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 16:20:07 +0000 Subject: [PATCH 05/13] test(plugin-sharing): the $nin pin names its predicate in where.id alone, on an object of its own A where with a second key reaches the gate in another shape, so it never exercised the by-id misreading; measured by ablating the gate. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../src/operator-id-write-gate-33928.test.ts | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts b/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts index 72fe7840913..e0c32f129cd 100644 --- a/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts +++ b/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts @@ -42,6 +42,8 @@ const OTHER = 'usr_opid_other'; const ORDER = 'qa_opid_order'; /** Owner-scoped (`private` OWD with an `owner_id`): record sharing enforces on it. */ const LINE = 'qa_opid_line'; +/** Owner-scoped like LINE, holding only the rows of the `$nin` pin, whose predicate names no other key. */ +const TAG = 'qa_opid_tag'; const SYSTEM = { isSystem: true, tenantId: ORG } as const; const SYS = { context: SYSTEM } as never; @@ -90,6 +92,12 @@ function objectsPlugin(): Plugin { name: 'Operator id write gate', objects: [ { name: ORDER, label: 'Order', sharingModel: 'public_read_write', fields: { name: { type: 'text', label: 'Name' } } }, + { + name: TAG, + label: 'Tag', + sharingModel: 'private', + fields: { name: { type: 'text', label: 'Name' }, owner_id: { type: 'text', label: 'Owner' } }, + }, { name: LINE, label: 'Line', @@ -199,15 +207,19 @@ describe('sharing write gate: an operator-valued id is a predicate write, never describe('another operator shape is scoped per matched row, never judged as a by-id string', () => { it('a `$nin` delete deletes only the matched rows the caller owns, and answers no error', async () => { - const { theirs } = await seedLines('n1'); - await ql.insert(LINE, { id: 'n1_kept', owner_id: ME, stage: 'n1' }, SYS); + // The whole predicate is `where.id`, as in the `$in` pins: the shape the gate used to judge by id. + await ql.insert(TAG, [ + { id: 'n1_mine1', owner_id: ME }, + { id: 'n1_mine2', owner_id: ME }, + { id: 'n1_theirs', owner_id: OTHER }, + { id: 'n1_kept', owner_id: ME }, + ], SYS); - const got = await outcomeOf(ql.delete( - LINE, { where: { id: { $nin: ['n1_kept'] }, stage: 'n1' }, multi: true, context: asCaller() } as never, - )); + const got = await outcomeOf(ql.delete(TAG, { where: { id: { $nin: ['n1_kept'] } }, multi: true, context: asCaller() } as never)); expect(got).toMatchObject({ kind: 'landed' }); - expect(await storedLines('n1')).toEqual(['n1_kept', theirs].sort()); + const rows = (await ql.find(TAG, { context: SYSTEM } as never)) as Array<{ id: string }>; + expect(rows.map((r) => String(r.id)).sort()).toEqual(['n1_kept', 'n1_theirs']); }); }); From eb28a95ed7902459a705941d3930f22f63827b07 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 16:47:04 +0000 Subject: [PATCH 06/13] test(plugin-sharing): pin $eq as the other operator shape, the one that reaches the gate as where.id The engine lowers $nin and $ne to a null-aware $and before any middleware, so neither ever met the by-id misreading. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../src/operator-id-write-gate-33928.test.ts | 26 +++++++++---------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts b/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts index e0c32f129cd..4073ea287cf 100644 --- a/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts +++ b/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts @@ -2,7 +2,7 @@ /** * The sharing write gate on a write whose `where.id` is an OPERATOR object - * (`{ $in: [...] }`, `{ $nin: [...] }`), not a row id. + * (`{ $in: [...] }`, `{ $eq: ... }`), not a row id. * * The gate used to stringify any `where.id` into the row it judged by id, so * `{ $in: ['row_1'] }` was judged as the row "[object Object]", which no caller @@ -20,7 +20,7 @@ * gives, the same refusal envelope, and deletes nothing. The gate does not * tell a cascade from a user's bulk write: whatever shape the engine deletes * a parent's children in, the child it may not delete refuses as by id; - * - another operator shape (`$nin`) is scoped per matched row by the same + * - another operator shape (`$eq`) is scoped per matched row by the same * filter, never judged as a by-id string; * - a scalar id is judged by id exactly as before. * @@ -42,7 +42,7 @@ const OTHER = 'usr_opid_other'; const ORDER = 'qa_opid_order'; /** Owner-scoped (`private` OWD with an `owner_id`): record sharing enforces on it. */ const LINE = 'qa_opid_line'; -/** Owner-scoped like LINE, holding only the rows of the `$nin` pin, whose predicate names no other key. */ +/** Owner-scoped like LINE, holding only the rows of the `$eq` pin. */ const TAG = 'qa_opid_tag'; const SYSTEM = { isSystem: true, tenantId: ORG } as const; @@ -206,20 +206,18 @@ describe('sharing write gate: an operator-valued id is a predicate write, never }); describe('another operator shape is scoped per matched row, never judged as a by-id string', () => { - it('a `$nin` delete deletes only the matched rows the caller owns, and answers no error', async () => { - // The whole predicate is `where.id`, as in the `$in` pins: the shape the gate used to judge by id. - await ql.insert(TAG, [ - { id: 'n1_mine1', owner_id: ME }, - { id: 'n1_mine2', owner_id: ME }, - { id: 'n1_theirs', owner_id: OTHER }, - { id: 'n1_kept', owner_id: ME }, - ], SYS); + it('an `$eq` delete of an owned row deletes it; of a not-owned row answers no error and leaves it', async () => { + // `$eq` reaches the gate as `where.id` itself; `$nin` / `$ne` do not (the engine lowers them to a + // null-aware `$and` first), so `$eq` is the other operator shape the gate used to judge by id. + await ql.insert(TAG, [{ id: 'e1_mine', owner_id: ME }, { id: 'e1_theirs', owner_id: OTHER }], SYS); - const got = await outcomeOf(ql.delete(TAG, { where: { id: { $nin: ['n1_kept'] } }, multi: true, context: asCaller() } as never)); + const mine = await outcomeOf(ql.delete(TAG, { where: { id: { $eq: 'e1_mine' } }, multi: true, context: asCaller() } as never)); + const theirs = await outcomeOf(ql.delete(TAG, { where: { id: { $eq: 'e1_theirs' } }, multi: true, context: asCaller() } as never)); - expect(got).toMatchObject({ kind: 'landed' }); + expect(mine).toMatchObject({ kind: 'landed' }); + expect(theirs).toMatchObject({ kind: 'landed' }); const rows = (await ql.find(TAG, { context: SYSTEM } as never)) as Array<{ id: string }>; - expect(rows.map((r) => String(r.id)).sort()).toEqual(['n1_kept', 'n1_theirs']); + expect(rows.map((r) => String(r.id)).sort()).toEqual(['e1_theirs']); }); }); From 9608616d65431240c139488e6a42f48b22bd0a6b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 17:45:54 +0000 Subject: [PATCH 07/13] fix(plugin-sharing): the write gate's by-id branch is the engine's own dispatch decision The gate judges by id exactly the writes the engine runs by id, and every other write meets the bulk write scope. The branch is taken from the engine's dispatch helpers for the same options bag, and the pins state the rule over every option shape the gate is handed. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../src/operator-id-write-gate-33928.test.ts | 123 ++++++++++++++---- .../plugin-sharing/src/sharing-plugin.ts | 53 +++----- 2 files changed, 118 insertions(+), 58 deletions(-) diff --git a/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts b/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts index 4073ea287cf..889af91a127 100644 --- a/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts +++ b/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts @@ -1,38 +1,33 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * The sharing write gate on a write whose `where.id` is an OPERATOR object - * (`{ $in: [...] }`, `{ $eq: ... }`), not a row id. + * The sharing write gate judges BY ID exactly the writes the engine runs by + * id, and every other write meets the bulk write scope. * - * The gate used to stringify any `where.id` into the row it judged by id, so - * `{ $in: ['row_1'] }` was judged as the row "[object Object]", which no caller - * owns: a member's multi-row delete of rows it owns answered 403 FORBIDDEN and - * deleted nothing. Only a scalar id names a row now (the engine's own dispatch - * rule); any other value is a predicate, and takes the bulk branch: - * `SharingService.buildWriteFilter` ANDed into the predicate. + * The rule, as pinned here: * - * What each door answers, pinned here: + * - the by-id / bulk branch is the engine's own dispatch decision for the + * options bag the write carries, over every option shape the gate is + * handed (unit table below, against the middleware itself); + * - a scalar id the engine writes by id is judged by id, as before; + * - a write the engine runs as a predicate (`$in`, `$eq` on `id`) gets the + * answer every bulk write has (`buildWriteFilter`, ADR-0111 D3): the rows + * the caller may write are written, the others are left as they were, no + * error; + * - a cascade delete gives the answer the by-id delete of a refused child + * gives, the same refusal envelope, and deletes nothing, whatever shape the + * engine deletes a parent's children in. * - * - a user's bulk write over rows it owns and rows it does not keeps the - * answer every bulk write has (`buildWriteFilter`, ADR-0111 D3): fewer - * rows, no error. The rows it may not write are left as they were; - * - a cascade delete gives the answer the by-id delete of the refused child - * gives, the same refusal envelope, and deletes nothing. The gate does not - * tell a cascade from a user's bulk write: whatever shape the engine deletes - * a parent's children in, the child it may not delete refuses as by id; - * - another operator shape (`$eq`) is scoped per matched row by the same - * filter, never judged as a by-id string; - * - a scalar id is judged by id exactly as before. - * - * Real stack: an `ObjectKernel` with `ObjectQLPlugin` over better-sqlite3 and - * `SharingServicePlugin`, so every answer is the middleware the engine runs. + * Real stack for the door answers: an `ObjectKernel` with `ObjectQLPlugin` over + * better-sqlite3 and `SharingServicePlugin`, so every answer is the middleware + * the engine runs. */ -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; -import { SharingServicePlugin } from './sharing-plugin.js'; +import { SharingServicePlugin, buildSharingMiddleware } from './sharing-plugin.js'; const ORG = 'org_opid'; const ME = 'usr_opid_me'; @@ -115,7 +110,7 @@ function objectsPlugin(): Plugin { }; } -describe('sharing write gate: an operator-valued id is a predicate write, never the row "[object Object]"', () => { +describe('sharing write gate: a write the engine runs as a predicate meets the bulk write scope (real stack)', () => { let kernel: ObjectKernel; let ql: ObjectQL; @@ -205,7 +200,7 @@ describe('sharing write gate: an operator-valued id is a predicate write, never }); }); - describe('another operator shape is scoped per matched row, never judged as a by-id string', () => { + describe('another predicate on id is scoped per matched row by the same bulk scope', () => { it('an `$eq` delete of an owned row deletes it; of a not-owned row answers no error and leaves it', async () => { // `$eq` reaches the gate as `where.id` itself; `$nin` / `$ne` do not (the engine lowers them to a // null-aware `$and` first), so `$eq` is the other operator shape the gate used to judge by id. @@ -251,3 +246,79 @@ describe('sharing write gate: an operator-valued id is a predicate write, never }); }); }); + +/** + * The branch, over every option shape the gate is handed. Each row is the + * options bag (and payload) of one write and the branch the ENGINE dispatches + * it to (`by-id` with the row it binds, or `bulk`), written out here rather + * than computed, so the table is a statement of the rule and not a copy of + * the code under test. + */ +describe('sharing write gate: the by-id branch is exactly the engine dispatch decision', () => { + const CALLER = { userId: 'u_member', tenantId: 'org_1' }; + type Branch = { kind: 'by-id'; id: string } | { kind: 'bulk' }; + type Row = readonly [verb: 'update' | 'delete', data: Record | undefined, options: Record, branch: Branch]; + const BY = (id: string): Branch => ({ kind: 'by-id', id }); + const BULK: Branch = { kind: 'bulk' }; + const IN = { $in: ['r_1', 'r_2'] }; + + const ROWS: readonly Row[] = [ + // where.id scalar: by id, with or without multi. + ['delete', undefined, { where: { id: 'r_1' } }, BY('r_1')], + ['delete', undefined, { where: { id: 'r_1' }, multi: true }, BY('r_1')], + ['update', { stage: 'x' }, { where: { id: 'r_1' } }, BY('r_1')], + ['update', { stage: 'x' }, { where: { id: 'r_1' }, multi: true }, BY('r_1')], + // where.id a predicate: bulk, with or without multi. + ['delete', undefined, { where: { id: IN } }, BULK], + ['delete', undefined, { where: { id: IN }, multi: true }, BULK], + ['update', { stage: 'x' }, { where: { id: IN } }, BULK], + ['update', { stage: 'x' }, { where: { id: IN }, multi: true }, BULK], + // data.id: the payload id the engine binds for an update. + ['update', { id: 'r_1', stage: 'x' }, {}, BY('r_1')], + ['update', { id: 'r_1', stage: 'x' }, { multi: true }, BY('r_1')], + ['update', { id: IN, stage: 'x' }, { where: { stage: 'open' }, multi: true }, BULK], + // options.id: no engine dispatch routes on it. + ['delete', undefined, { id: 'r_1' }, BULK], + ['delete', undefined, { id: 'r_1', where: { stage: 'open' }, multi: true }, BULK], + ['update', { stage: 'x' }, { id: 'r_1' }, BULK], + ['update', { stage: 'x' }, { id: 'r_1', where: { stage: 'open' }, multi: true }, BULK], + // options.filter.id: no engine dispatch routes on it. + ['delete', undefined, { filter: { id: 'r_1' } }, BULK], + ['delete', undefined, { filter: { id: 'r_1' }, where: { stage: 'open' }, multi: true }, BULK], + ['delete', undefined, { filter: { id: 'r_1' }, where: { id: IN }, multi: true }, BULK], + ['update', { stage: 'x' }, { filter: { id: 'r_1' }, where: { stage: 'open' }, multi: true }, BULK], + ['update', { stage: 'x' }, { filter: { id: 'r_1' }, where: { id: IN }, multi: true }, BULK], + // where.id scalar beside another predicate key under multi: the engine runs a predicate. + ['delete', undefined, { where: { id: 'r_1', stage: 'open' }, multi: true }, BULK], + ['update', { stage: 'x' }, { where: { id: 'r_1', stage: 'open' }, multi: true }, BULK], + ]; + + function service() { + return { + admitsByIdWrite: vi.fn(async () => true), + buildWriteFilter: vi.fn(async () => ({ owner_id: 'u_member' })), + }; + } + + it.each(ROWS)('a %s write meets the branch the engine dispatches it to (row %#)', async (verb, data, options, branch) => { + const svc = service(); + const mw = buildSharingMiddleware(svc as never, { warn: () => {} } as never) as unknown as ( + ctx: Record, next: () => Promise, + ) => Promise; + const bag = { ...options, context: CALLER }; + const ctx: Record = { object: 'deal', operation: verb, options: bag, context: CALLER, ...(data ? { data } : {}) }; + let reached = false; + + await mw(ctx, async () => { reached = true; }); + + expect(reached).toBe(true); + if (branch.kind === 'by-id') { + expect(svc.admitsByIdWrite).toHaveBeenCalledWith('deal', branch.id, verb, CALLER); + expect(svc.buildWriteFilter).not.toHaveBeenCalled(); + } else { + expect(svc.admitsByIdWrite).not.toHaveBeenCalled(); + expect(svc.buildWriteFilter).toHaveBeenCalledWith('deal', CALLER, verb); + expect(JSON.stringify((ctx.ast as { where?: unknown } | undefined)?.where)).toContain('"owner_id":"u_member"'); + } + }); +}); diff --git a/packages/plugins/plugin-sharing/src/sharing-plugin.ts b/packages/plugins/plugin-sharing/src/sharing-plugin.ts index 2379c1a7bda..3dc73c4bff0 100644 --- a/packages/plugins/plugin-sharing/src/sharing-plugin.ts +++ b/packages/plugins/plugin-sharing/src/sharing-plugin.ts @@ -28,6 +28,7 @@ import { credentialUseClientFor, } from '@objectstack/core'; import type { EngineMiddleware, OperationContext } from '@objectstack/objectql'; +import { resolveEngineDeleteDispatch, resolveEngineUpdateDispatch } from '@objectstack/objectql'; import type { AuthSessionApi, IAuthService, @@ -1542,7 +1543,7 @@ export function buildSharingMiddleware( const verb: 'update' | 'delete' = writeClass; const data: any = ctx.data; const options: any = ctx.options; - const id = inferTargetId(data, options); + const id = engineByIdTarget(verb, data, options); // [#30237] The recycle bin's own doors — `restore(entryId)`, // `purge(entryId)`, `empty(object)` — dispatch their verb with no id and // no AST: they address no live row, so there is no row to gate and no @@ -1774,37 +1775,25 @@ function composeAnd(existing: unknown, addition: unknown): unknown { } /** - * The ONE row a write addresses, or `undefined` when it addresses a predicate. + * The row the ENGINE writes by id, or `undefined` when the engine runs the + * write as a predicate over the AST it seeded from `where`. * - * Only a SCALAR id (string, number, bigint) names a row, the engine's own rule - * for picking the by-id route (`scalarDeleteId` / `scalarUpdateId` in - * `@objectstack/metadata-core`). An operator object (`{ $in: [...] }`, - * `{ $nin: [...] }`, `{ $eq: ... }`), an array or `null` in an id slot is a - * predicate over rows, which the engine dispatches to `deleteMany` / - * `updateMany` with the composed AST, so it takes the bulk branch of the write - * gate: the `buildWriteFilter` scope ANDed into that AST, the answer a bulk - * write has always had (fewer rows, no error). It is never stringified into a - * row id: `String({ $in: [...] })` is the row "[object Object]", which no - * caller owns, so every such write was refused whatever rows it named. A - * non-scalar slot does not shadow a later scalar one, as in the engine. + * The rule: this gate judges by id exactly the writes the engine runs by id, + * and every other write meets the bulk scope (`buildWriteFilter`). So the + * branch is the engine's own dispatch decision, made by the helpers its + * `delete()` / `update()` call on the same options bag + * (`resolveEngineDeleteDispatch` / `resolveEngineUpdateDispatch`), never a + * reading of option slots of this gate's own: an option the engine does not + * route on names no row here either. */ -function inferTargetId(data: any, options: any): string | number | bigint | undefined { - const slots: unknown[] = []; - if (data && typeof data === 'object') slots.push(data.id); - if (options && typeof options === 'object') { - slots.push(options.id); - if (options.where && typeof options.where === 'object') slots.push(options.where.id); - if (options.filter && typeof options.filter === 'object') slots.push(options.filter.id); - } - for (const slot of slots) { - const id = scalarIdOf(slot); - if (id !== undefined) return id; - } - return undefined; -} - -/** `value` when it is a scalar row id, `undefined` for an operator object, an array or anything else. */ -function scalarIdOf(value: unknown): string | number | bigint | undefined { - const t = typeof value; - return t === 'string' || t === 'number' || t === 'bigint' ? (value as string | number | bigint) : undefined; +function engineByIdTarget( + verb: 'update' | 'delete', + data: unknown, + options: unknown, +): string | number | bigint | undefined { + const bag = (options && typeof options === 'object' ? options : undefined) as Record | undefined; + const dispatch = verb === 'delete' + ? resolveEngineDeleteDispatch(bag) + : resolveEngineUpdateDispatch((data && typeof data === 'object' ? data : {}) as Record, bag); + return dispatch.kind === 'by-id' ? dispatch.id : undefined; } From a146693412bcb68cc855af67285f050bf4a24817 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 17:46:09 +0000 Subject: [PATCH 08/13] chore(changeset): state the plugin-sharing write-gate rule Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .changeset/33928-operator-id-write-gate.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.changeset/33928-operator-id-write-gate.md b/.changeset/33928-operator-id-write-gate.md index d646bbb58de..952c5f3427f 100644 --- a/.changeset/33928-operator-id-write-gate.md +++ b/.changeset/33928-operator-id-write-gate.md @@ -2,11 +2,11 @@ '@objectstack/plugin-sharing': patch --- -fix(plugin-sharing): a write whose `where.id` is an operator object is scoped as the predicate it is, not judged as the row "[object Object]" +fix(plugin-sharing): the write gate judges by id exactly the writes the engine runs by id Clause-②: yes (widening): a request refused today lands when every matched row is admitted; measured again by the dev before the PR Metadata-protocol: none -The sharing write gate turned any `where.id` into the one row it judged by id, so `{ $in: [...] }` was judged as the row "[object Object]", which no caller owns. A member's multi-row delete or update of rows it owns, on a `private` or `public_read` object with an `owner_id`, answered 403 FORBIDDEN and wrote nothing. +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. -Only a scalar id (string, number, bigint) now names the row the by-id gate judges, the rule the engine already uses to pick its by-id route. Any other value in an id slot (`$in`, `$nin`, `$eq`, an array) is a predicate, and gets the answer every bulk write gets: the writable-rows filter is ANDed into it, so the write touches only the rows the caller may update or delete, and the rest are left as they were, with no error. A by-id write with a scalar id is judged exactly as before. +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. From 8d3057c2b3ad461092428610581938365afd615a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 18:08:25 +0000 Subject: [PATCH 09/13] fix(plugin-sharing): the gate's by-id row is a scalar the engine binds; the by-id verdict pin drives each verb in the engine's shape Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- packages/plugins/plugin-sharing/src/sharing-plugin.ts | 5 ++++- packages/plugins/plugin-sharing/src/sharing-service.test.ts | 6 +++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/packages/plugins/plugin-sharing/src/sharing-plugin.ts b/packages/plugins/plugin-sharing/src/sharing-plugin.ts index 3dc73c4bff0..67b68073f67 100644 --- a/packages/plugins/plugin-sharing/src/sharing-plugin.ts +++ b/packages/plugins/plugin-sharing/src/sharing-plugin.ts @@ -1795,5 +1795,8 @@ function engineByIdTarget( const dispatch = verb === 'delete' ? resolveEngineDeleteDispatch(bag) : resolveEngineUpdateDispatch((data && typeof data === 'object' ? data : {}) as Record, bag); - return dispatch.kind === 'by-id' ? dispatch.id : undefined; + if (dispatch.kind !== 'by-id') return undefined; + const id: unknown = dispatch.id; + // The engine binds a by-id write to a scalar key; anything else is no row to judge by id. + return typeof id === 'string' || typeof id === 'number' || typeof id === 'bigint' ? id : undefined; } diff --git a/packages/plugins/plugin-sharing/src/sharing-service.test.ts b/packages/plugins/plugin-sharing/src/sharing-service.test.ts index 19637f8cbc6..adf1068255a 100644 --- a/packages/plugins/plugin-sharing/src/sharing-service.test.ts +++ b/packages/plugins/plugin-sharing/src/sharing-service.test.ts @@ -754,7 +754,11 @@ describe('buildSharingMiddleware (engine integration)', () => { await svc.grant({ object: 'account', recordId: 'a2', recipientId: 'alice', accessLevel: 'edit' }, { isSystem: true }); const mw = buildSharingMiddleware(svc); const passes = (operation: 'update' | 'delete', id: string, userId: string) => - mw({ object: 'account', operation, data: { id }, context: { userId } } as any, async () => {}).then(() => true, (e: any) => { + // Each verb in the shape the engine hands its middleware: an update binds the payload id, a delete `where.id`. + mw({ + object: 'account', operation, context: { userId }, + ...(operation === 'update' ? { data: { id } } : { options: { where: { id } } }), + } as any, async () => {}).then(() => true, (e: any) => { expect(e).toMatchObject({ code: 'FORBIDDEN', status: 403 }); return false; }); From b1d5f9a4fbc52121e1b78ad2ef96458ab9b523e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 18:09:05 +0000 Subject: [PATCH 10/13] test(plugin-sharing): name the dispatch-table pin by its rule Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../plugin-sharing/src/operator-id-write-gate-33928.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts b/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts index 889af91a127..a921898519d 100644 --- a/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts +++ b/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts @@ -300,7 +300,7 @@ describe('sharing write gate: the by-id branch is exactly the engine dispatch de }; } - it.each(ROWS)('a %s write meets the branch the engine dispatches it to (row %#)', async (verb, data, options, branch) => { + it.each(ROWS)('%s: the gate takes the branch the engine dispatches the write to (row %#)', async (verb, data, options, branch) => { const svc = service(); const mw = buildSharingMiddleware(svc as never, { warn: () => {} } as never) as unknown as ( ctx: Record, next: () => Promise, From 1d2ce02775b5fd7847b6c00b64e78697a9e89ce5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 22:05:40 +0000 Subject: [PATCH 11/13] test(plugin-sharing): pin every predicate write shape at the door, and the falsy-id and refused rows of the dispatch table Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .../src/vama-write-path-convergence.test.ts | 6 +- .../src/operator-id-write-gate-33928.test.ts | 76 +++++++++++++++++++ 2 files changed, 79 insertions(+), 3 deletions(-) diff --git a/packages/plugins/plugin-security/src/vama-write-path-convergence.test.ts b/packages/plugins/plugin-security/src/vama-write-path-convergence.test.ts index c08d55d5a4b..0bb7bb87f49 100644 --- a/packages/plugins/plugin-security/src/vama-write-path-convergence.test.ts +++ b/packages/plugins/plugin-security/src/vama-write-path-convergence.test.ts @@ -392,9 +392,9 @@ describe('[#4647] VAMA holder + private OWD + ownerless record — explain vs. t await expect(makeEngine().delete('crm_contract', { id: OWNERLESS.id })).rejects.toThrow( ENGINE_DELETE_REJECT_MESSAGE, ); - // The asymmetry that let it hide for so long: plugin-sharing's - // `inferTargetId` DOES accept `options.id`, so `canDelete` kept running and - // kept answering — one of the two gates, doing the work of two. + // `canDelete` itself still answers for the row: the sharing write gate + // takes its by-id branch from the engine's own dispatch decision, so it + // judges by id only what the engine writes by id, and this bag is not one. expect(await stack.sharing.canDelete('crm_contract', OWNERLESS.id, MEMBER_CTX as any)).toBe(false); }); diff --git a/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts b/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts index a921898519d..fe0a767ada8 100644 --- a/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts +++ b/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts @@ -216,6 +216,72 @@ describe('sharing write gate: a write the engine runs as a predicate meets the b }); }); + describe('every write the engine runs as a predicate meets the bulk scope at the door', () => { + const delMany = (where: Record, context: unknown = asCaller()) => + outcomeOf(ql.delete(LINE, { where, multi: true, context } as never)); + const updMany = (where: Record, data: Record, context: unknown = asCaller()) => + outcomeOf(ql.update(LINE, data, { where, multi: true, context } as never)); + const stageOf = async (id: string) => + ((await ql.find(LINE, { where: { id }, context: SYSTEM } as never)) as Array<{ stage?: string }>)[0]?.stage; + + it('a scalar id beside another predicate key writes the row only when the caller may write it', async () => { + const { mine, theirs } = await seedLines('p1'); + + expect(await delMany({ id: theirs, stage: 'p1' })).toMatchObject({ kind: 'landed' }); + expect(await delMany({ id: mine[0], stage: 'p1' })).toMatchObject({ kind: 'landed' }); + expect(await updMany({ id: theirs, stage: 'p1' }, { name: 'written' })).toMatchObject({ kind: 'landed' }); + expect(await updMany({ id: mine[1], stage: 'p1' }, { stage: 'p1_written' })).toMatchObject({ kind: 'landed' }); + + expect(await storedLines('p1')).toEqual([mine[1], theirs].sort()); + expect(await stageOf(mine[1])).toBe('p1_written'); + const other = ((await ql.find(LINE, { where: { id: theirs }, context: SYSTEM } as never)) as Array<{ name?: string }>)[0]; + expect(other?.name ?? null).not.toBe('written'); + }); + + it('a falsy id names no row: no error, nothing written', async () => { + const { mine, theirs } = await seedLines('p2'); + + expect(await delMany({ id: '' })).toMatchObject({ kind: 'landed' }); + expect(await delMany({ id: 0 })).toMatchObject({ kind: 'landed' }); + expect(await updMany({ id: '' }, { stage: 'p2_written' })).toMatchObject({ kind: 'landed' }); + + expect(await storedLines('p2')).toEqual([...mine, theirs].sort()); + for (const id of [...mine, theirs]) expect(await stageOf(id)).toBe('p2'); + }); + + it('an empty `$in` matches no row: no error, nothing written', async () => { + const { mine, theirs } = await seedLines('p3'); + + expect(await delMany({ id: { $in: [] } })).toMatchObject({ kind: 'landed' }); + expect(await updMany({ id: { $in: [] } }, { stage: 'p3_written' })).toMatchObject({ kind: 'landed' }); + + expect(await storedLines('p3')).toEqual([...mine, theirs].sort()); + for (const id of [...mine, theirs]) expect(await stageOf(id)).toBe('p3'); + }); + + it('a read share admits no write: an `$eq` or `$in` update of a read-shared row writes nothing', async () => { + await ql.insert(LINE, { id: 'p4_read', owner_id: OTHER, stage: 'p4' }, SYS); + await shareToMe('p4_read', 'read'); + expect(await ql.findOne(LINE, { where: { id: 'p4_read' }, context: asCaller() } as never)).toMatchObject({ id: 'p4_read' }); + + expect(await updMany({ id: { $eq: 'p4_read' } }, { stage: 'p4_written' })).toMatchObject({ kind: 'landed' }); + expect(await updMany({ id: { $in: ['p4_read'] } }, { stage: 'p4_written' })).toMatchObject({ kind: 'landed' }); + + expect(await stageOf('p4_read')).toBe('p4'); + }); + + it('control: the system context writes every row the predicate matches', async () => { + const { mine, theirs } = await seedLines('p5'); + + expect(await updMany({ id: { $in: [...mine, theirs] } }, { stage: 'p5_written' }, SYSTEM)).toMatchObject({ kind: 'landed' }); + for (const id of [...mine, theirs]) expect(await stageOf(id)).toBe('p5_written'); + expect(await delMany({ id: theirs, stage: 'p5_written' }, SYSTEM)).toMatchObject({ kind: 'landed' }); + expect(await delMany({ id: { $in: mine } }, SYSTEM)).toMatchObject({ kind: 'landed' }); + + expect(await storedLines('p5')).toEqual([]); + }); + }); + describe('a cascade delete gives the answer the by-id delete of the refused child gives', () => { it('a child the caller reads and may edit but not delete: the same refusal envelope, and nothing is deleted', async () => { await ql.insert(ORDER, { id: 'c1', name: 'c1' }, SYS); @@ -291,6 +357,16 @@ describe('sharing write gate: the by-id branch is exactly the engine dispatch de // where.id scalar beside another predicate key under multi: the engine runs a predicate. ['delete', undefined, { where: { id: 'r_1', stage: 'open' }, multi: true }, BULK], ['update', { stage: 'x' }, { where: { id: 'r_1', stage: 'open' }, multi: true }, BULK], + // A falsy scalar id names no row for the engine. + ['delete', undefined, { where: { id: '' }, multi: true }, BULK], + ['delete', undefined, { where: { id: 0 }, multi: true }, BULK], + ['update', { stage: 'x' }, { where: { id: '' }, multi: true }, BULK], + ['update', { id: '', stage: 'x' }, { where: { stage: 'open' }, multi: true }, BULK], + // Calls the engine refuses at dispatch: no row is written by id. + ['delete', undefined, { where: { id: 'r_1', stage: 'open' } }, BULK], + ['update', { stage: 'x' }, { where: { id: 'r_1', stage: 'open' } }, BULK], + ['update', { id: 'r_1', stage: 'x' }, { where: { stage: 'open' } }, BULK], + ['update', { id: 'r_1', stage: 'x' }, { where: { stage: 'open' }, multi: true }, BULK], ]; function service() { From 185f9d424474f8863ecbb6608e94d4a0f95a8fa4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 22:36:32 +0000 Subject: [PATCH 12/13] chore(changeset): declare the plugin-sharing write-gate narrowing for the two predicate shapes Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .changeset/33928-operator-id-write-gate.md | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/.changeset/33928-operator-id-write-gate.md b/.changeset/33928-operator-id-write-gate.md index 952c5f3427f..3be3224ef1f 100644 --- a/.changeset/33928-operator-id-write-gate.md +++ b/.changeset/33928-operator-id-write-gate.md @@ -2,11 +2,26 @@ '@objectstack/plugin-sharing': patch --- -fix(plugin-sharing): the write gate judges by id exactly the writes the engine runs by id +fix(plugin-sharing)!: the write gate judges by id exactly the writes the engine runs by id -Clause-②: yes (widening): a request refused today lands when every matched row is admitted; measured again by the dev before the PR +Clause-②: no (narrowing) Metadata-protocol: none +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. + + 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. 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. + +**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: + +- a `where` that carries a scalar `id` beside another key; +- an `id` that is falsy (`''` or `0`). + +Such a write meets the bulk write scope instead of the by-id judgment: + +- a row the caller may not write is left as it was, and the write answers no error where it answered 403 FORBIDDEN; +- a row the caller may write only because an application row-level policy widens the sharing scope for it (the by-id judgment's deferral to such a policy) is no longer written by these two shapes, as for every other predicate write. + +To write such a row, address it by id alone (`where: { id }`, or the payload `id`): that write is judged by id, as before. From 00cff2ba9051e9998f30f31fc8b4bb899ea9abba Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:17:59 +0000 Subject: [PATCH 13/13] 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 Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --- .changeset/33928-operator-id-write-gate.md | 3 +- .../src/operator-id-write-gate-33928.test.ts | 185 ++++++++++++++++++ .../src/operator-id-write-gate-33928.test.ts | 49 ++++- 3 files changed, 234 insertions(+), 3 deletions(-) create mode 100644 packages/plugins/plugin-security/src/operator-id-write-gate-33928.test.ts diff --git a/.changeset/33928-operator-id-write-gate.md b/.changeset/33928-operator-id-write-gate.md index 3be3224ef1f..9b69198fa92 100644 --- a/.changeset/33928-operator-id-write-gate.md +++ b/.changeset/33928-operator-id-write-gate.md @@ -6,7 +6,6 @@ fix(plugin-sharing)!: the write gate judges by id exactly the writes the engine Clause-②: no (narrowing) Metadata-protocol: none -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. @@ -14,6 +13,8 @@ The sharing write gate now takes its by-id or bulk branch from the engine's own 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. +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. + **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: - a `where` that carries a scalar `id` beside another key; diff --git a/packages/plugins/plugin-security/src/operator-id-write-gate-33928.test.ts b/packages/plugins/plugin-security/src/operator-id-write-gate-33928.test.ts new file mode 100644 index 00000000000..5b1a7719172 --- /dev/null +++ b/packages/plugins/plugin-security/src/operator-id-write-gate-33928.test.ts @@ -0,0 +1,185 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The declared narrowing of the sharing write gate, with plugin-security composed in. + * + * Under `multi: true`, a scalar `where.id` beside another `where` key is a write + * the engine runs as a predicate. The sharing write gate judges it by the bulk + * write scope, as it judges every predicate write, and not by id. + * + * Two answers are pinned on the same row, side by side: + * + * - the narrowed answer: a row the caller may write only because an + * application row-level policy widens the sharing scope for it is not + * written by that shape, and the write answers no error; + * - the remedy: the same row, addressed by id alone, is judged by id and + * written. + * + * Real stack: an `ObjectKernel` with `ObjectQLPlugin` over better-sqlite3, the + * platform permission sets plus an application writer set with a row-level + * update/delete policy, `SecurityPlugin` and `SharingServicePlugin`. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SharingServicePlugin } from '@objectstack/plugin-sharing'; +import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { SecurityPlugin } from './security-plugin.js'; +import { defaultPermissionSets } from './objects/default-permission-sets.js'; + +const ORG = 'org_opidc'; +const ME = 'usr_opidc_me'; +const OTHER = 'usr_opidc_other'; +/** Owner-scoped (`private` OWD with an `owner_id`): record sharing enforces on it. */ +const DEAL = 'qa_opidc_deal'; + +const CRUD = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } as const; +/** The application's writer set: a row-level policy admits an update or delete of any `open` deal. */ +const WRITER = PermissionSetSchema.parse({ + name: 'qa_opidc_writer', + objects: { [DEAL]: CRUD }, + rowLevelSecurity: [ + { name: 'qa_opidc_open_updates', object: DEAL, operation: 'update', using: "stage == 'open'" }, + { name: 'qa_opidc_open_deletes', object: DEAL, operation: 'delete', using: "stage == 'open'" }, + ], +}); + +const SYSTEM = { isSystem: true, tenantId: ORG } as const; +const SYS = { context: SYSTEM } as never; +const asCaller = () => ({ userId: ME, tenantId: ORG, positions: [], permissions: [WRITER.name] }); + +type Outcome = { kind: 'landed' } | { kind: 'refused'; code?: string; status?: number }; +const outcomeOf = (p: Promise): Promise => + p.then( + () => ({ kind: 'landed' as const }), + (e: { code?: unknown; status?: unknown; statusCode?: unknown } | null) => { + const status = e?.statusCode ?? e?.status; + return { + kind: 'refused' as const, + code: e?.code == null ? undefined : String(e.code), + status: status == null ? undefined : Number(status), + }; + }, + ); + +function sqliteDriverPlugin(): Plugin { + return { + name: 'test.driver.sqlite', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService( + 'driver.default', + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + ); + }, + }; +} + +function objectsPlugin(): Plugin { + return { + name: 'test.objects', + type: 'standard', + version: '1.0.0', + dependencies: ['com.objectstack.engine.objectql'], + async init(ctx: PluginContext) { + ctx.getService<{ register(m: unknown): unknown }>('manifest').register({ + id: 'test.operator-id-write-gate-composed', + namespace: 'qa_opidc', + version: '1.0.0', + type: 'plugin', + name: 'Operator id write gate, composed', + objects: [ + SysUser, SysMember, SysOrganization, + { + name: DEAL, + label: 'Deal', + sharingModel: 'private', + fields: { + name: { type: 'text', label: 'Name' }, + stage: { type: 'text', label: 'Stage' }, + owner_id: { type: 'lookup', reference: 'sys_user', label: 'Owner' }, + }, + }, + ], + }); + }, + }; +} + +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', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + + beforeAll(async () => { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as never); + await kernel.use(sqliteDriverPlugin()); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(objectsPlugin()); + await kernel.use(new SecurityPlugin({ + defaultPermissionSets: [...defaultPermissionSets, WRITER], + fallbackPermissionSet: 'member_default', + })); + await kernel.use(new SharingServicePlugin({ registerShareLinkRoutes: false })); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + + await ql.insert('sys_organization', { id: ORG, name: 'Acme', slug: 'acme' }, SYS); + for (const userId of [ME, OTHER]) { + await ql.insert('sys_user', { id: userId, name: userId, email: `${userId}@acme.test`, email_verified: true }, SYS); + await ql.insert('sys_member', { user_id: userId, organization_id: ORG, role: 'member' }, SYS); + } + }, 120_000); + + afterAll(async () => { + if (kernel) await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + }, 30_000); + + const stored = async (id: string) => + ((await ql.find(DEAL, { where: { id }, context: SYSTEM } as never)) as Array<{ name?: string }>)[0] ?? null; + + /** + * Another member's `open` deal, shared to the caller for reading only. Record + * sharing does not let the caller write it; the application's row-level + * policy does. + */ + const seedPolicyAdmittedRow = async (id: string) => { + await ql.insert(DEAL, { id, owner_id: OTHER, created_by: OTHER, stage: 'open', name: 'seed' }, SYS); + await ql.insert('sys_record_share', { + object_name: DEAL, record_id: id, recipient_type: 'user', recipient_id: ME, + access_level: 'read', source: 'manual', + }, SYS); + expect(await ql.findOne(DEAL, { where: { id }, context: asCaller() } as never)).toMatchObject({ id }); + }; + + it('update: the two-key predicate answers no error and leaves the row; the same row by id alone is written', async () => { + await seedPolicyAdmittedRow('u_1'); + + const narrowed = await outcomeOf( + ql.update(DEAL, { name: 'by_predicate' }, { where: { id: 'u_1', stage: 'open' }, multi: true, context: asCaller() } as never), + ); + expect(narrowed).toEqual({ kind: 'landed' }); + expect(await stored('u_1')).toMatchObject({ name: 'seed' }); + + const byId = await outcomeOf(ql.update(DEAL, { name: 'by_id' }, { where: { id: 'u_1' }, context: asCaller() } as never)); + expect(byId).toEqual({ kind: 'landed' }); + expect(await stored('u_1')).toMatchObject({ name: 'by_id' }); + }); + + it('delete: the two-key predicate answers no error and leaves the row; the same row by id alone is deleted', async () => { + await seedPolicyAdmittedRow('d_1'); + + const narrowed = await outcomeOf( + ql.delete(DEAL, { where: { id: 'd_1', stage: 'open' }, multi: true, context: asCaller() } as never), + ); + expect(narrowed).toEqual({ kind: 'landed' }); + expect(await stored('d_1')).not.toBeNull(); + + const byId = await outcomeOf(ql.delete(DEAL, { where: { id: 'd_1' }, context: asCaller() } as never)); + expect(byId).toEqual({ kind: 'landed' }); + expect(await stored('d_1')).toBeNull(); + }); +}); diff --git a/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts b/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts index fe0a767ada8..61edff5cea8 100644 --- a/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts +++ b/packages/plugins/plugin-sharing/src/operator-id-write-gate-33928.test.ts @@ -238,18 +238,20 @@ describe('sharing write gate: a write the engine runs as a predicate meets the b expect(other?.name ?? null).not.toBe('written'); }); - it('a falsy id names no row: no error, nothing written', async () => { + it('a falsy id: the answer is no error (it names no row, so nothing is written)', async () => { const { mine, theirs } = await seedLines('p2'); expect(await delMany({ id: '' })).toMatchObject({ kind: 'landed' }); expect(await delMany({ id: 0 })).toMatchObject({ kind: 'landed' }); expect(await updMany({ id: '' }, { stage: 'p2_written' })).toMatchObject({ kind: 'landed' }); + expect(await updMany({ id: 0 }, { stage: 'p2_written' })).toMatchObject({ kind: 'landed' }); + expect(await updMany({ stage: 'p2_none' }, { id: '', stage: 'p2_written' })).toMatchObject({ kind: 'landed' }); expect(await storedLines('p2')).toEqual([...mine, theirs].sort()); for (const id of [...mine, theirs]) expect(await stageOf(id)).toBe('p2'); }); - it('an empty `$in` matches no row: no error, nothing written', async () => { + it('an empty `$in`: the answer is no error (it matches no row, so nothing is written)', async () => { const { mine, theirs } = await seedLines('p3'); 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 expect(await stageOf('p4_read')).toBe('p4'); }); + it('control: an `$eq` update of a row the caller owns writes it', async () => { + const { mine, theirs } = await seedLines('p7'); + + expect(await updMany({ id: { $eq: mine[0] } }, { stage: 'p7_written' })).toMatchObject({ kind: 'landed' }); + + expect(await stageOf(mine[0])).toBe('p7_written'); + expect(await stageOf(mine[1])).toBe('p7'); + expect(await stageOf(theirs)).toBe('p7'); + }); + + 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 () => { + const { mine, theirs } = await seedLines('p6'); + const refusalOf = (p: Promise) => + p.then( + () => ({ kind: 'landed' as const }), + (e: { code?: unknown; status?: unknown; message?: unknown } | null) => ({ + kind: 'refused' as const, + code: e?.code == null ? undefined : String(e.code), + status: e?.status == null ? undefined : Number(e.status), + message: String(e?.message), + }), + ); + // A scalar id beside another where key, without `multi`. + const del = (context: unknown) => refusalOf(ql.delete(LINE, { where: { id: theirs, stage: 'p6' }, context } as never)); + const upd = (context: unknown) => + refusalOf(ql.update(LINE, { stage: 'p6_written' }, { where: { id: theirs, stage: 'p6' }, context } as never)); + // A payload id beside a where predicate. + const updPayload = (context: unknown) => + refusalOf(ql.update(LINE, { id: theirs, stage: 'p6_written' }, { where: { stage: 'p6' }, context } as never)); + + for (const call of [del, upd, updPayload]) { + const asSystem = await call(SYSTEM); + const asMember = await call(asCaller()); + expect(asSystem).toMatchObject({ kind: 'refused' }); + expect(asMember).toEqual(asSystem); + expect(asMember).not.toMatchObject({ code: 'FORBIDDEN' }); + expect(asMember).not.toMatchObject({ status: 403 }); + } + + expect(await storedLines('p6')).toEqual([...mine, theirs].sort()); + for (const id of [...mine, theirs]) expect(await stageOf(id)).toBe('p6'); + }); + it('control: the system context writes every row the predicate matches', async () => { const { mine, theirs } = await seedLines('p5');