Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
3000c91
fix(plugin-sharing): an operator-valued id is a predicate write, scop…
claude Nov 15, 2026
7ba0bb7
test(plugin-sharing): pin the write gate's answer to an operator-valu…
claude Nov 15, 2026
e9bd87c
test(plugin-sharing): name the operator-id pin file by its card
claude Nov 15, 2026
4bbcebd
chore(changeset): plugin-sharing patch for the operator-id write gate
claude Nov 15, 2026
665ed8b
test(plugin-sharing): the $nin pin names its predicate in where.id al…
claude Nov 15, 2026
eb28a95
test(plugin-sharing): pin $eq as the other operator shape, the one th…
claude Nov 15, 2026
6bed9e0
Merge remote-tracking branch 'origin/main' into claude/area-A2-33928
claude Nov 15, 2026
9608616
fix(plugin-sharing): the write gate's by-id branch is the engine's ow…
claude Nov 15, 2026
a146693
chore(changeset): state the plugin-sharing write-gate rule
claude Nov 15, 2026
8d3057c
fix(plugin-sharing): the gate's by-id row is a scalar the engine bind…
claude Nov 15, 2026
b1d5f9a
test(plugin-sharing): name the dispatch-table pin by its rule
claude Nov 15, 2026
1d2ce02
test(plugin-sharing): pin every predicate write shape at the door, an…
claude Nov 15, 2026
5b5c685
Merge remote-tracking branch 'origin/main' into claude/area-A2-33928
claude Nov 15, 2026
185f9d4
chore(changeset): declare the plugin-sharing write-gate narrowing for…
claude Nov 15, 2026
7f475b9
Merge remote-tracking branch 'origin/main' into claude/area-A2-33928
claude Nov 16, 2026
00cff2b
test(plugin-sharing): pin the declared narrowing beside its by-id rem…
claude Nov 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .changeset/33928-operator-id-write-gate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
'@objectstack/plugin-sharing': patch
---

fix(plugin-sharing)!: the write gate judges by id exactly the writes the engine runs by id

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

<!-- 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 -->

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.

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;
- 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.
Original file line number Diff line number Diff line change
@@ -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<unknown>): Promise<Outcome> =>
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>('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<void>((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();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

Expand Down
Loading
Loading