Skip to content
14 changes: 14 additions & 0 deletions .changeset/39415-assignment-rule-organization-stamp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/plugin-sharing': patch
---

fix(plugin-sharing): an assignment rule created from Setup is stamped with the administrator's organization instead of being refused with "Organization is required"

Clause-②: no
Metadata-protocol: none

Who sees it: an organization administrator creating an assignment rule in Setup → Assignment Rules, or through `POST /api/v1/data/sys_assignment_rule`.

- **Creating a rule no longer needs an organization in the request.** The form has no organization field, so every create was refused with `400 VALIDATION_FAILED` on `organization_id`. The rule now lands in the caller's active organization, the way a queue does.
- **A stored rule still always belongs to one organization.** The column is the platform's tenant column, created NOT NULL, and a create that would land in no organization is still refused naming `organization_id`. A create that names its organization is stored under it, as before, and on a walled deployment the tenant wall still refuses one outside the caller's organizations.
- `organization_id` on `sys_assignment_rule` is now the platform-provided tenant column, the one `sys_queue` carries: hidden in forms, with no label or help text of its own, and read-only. An update can no longer move a rule to another organization: the value is dropped with a warning and the rule stays where it is, as a queue does. Create the rule in the organization it belongs to instead.
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ import { ObjectSchema, Field } from '@objectstack/spec/data';
* entry (a strategy on a user target, `least_loaded` without `load`, …);
* a `criteria` or `load` the engine's CEL paths cannot compile; a user target
* who is not an active member of the rule's organization; a row with no
* organization. At insert time a target that no longer resolves leaves the
* organization (the row's own, else the caller's active one, which the
* platform's tenant column is stamped with). At insert time a target that no longer resolves leaves the
* record ownerless and is logged once — intake is never refused.
*
* Field `description`s here are ADMIN-FACING help text rendered under each
Expand Down Expand Up @@ -72,16 +73,23 @@ export const SysAssignmentRule = ObjectSchema.create({
},
},

// Non-null: a stored rule always belongs to one organization. A rule that
// reaches every organization is a DECLARED rule, never a row here.
//
// The organization is the platform's tenant column, the one `sys_queue`
// rides: it is not declared here, so registration injects it
// (`applySystemFields`) and an insert is stamped with the caller's active
// organization before it is stored (the driver's `injectTenantOnInsert`; a
// system write's is resolved by the engine first). Declaring the column
// ourselves, `required`, made the record validator demand it from the
// caller before that stamp could run, so a rule created from Setup, whose
// form has no organization input, was refused with "Organization is
// required". Non-null is held where it is enforced: the tenant column is
// created NOT NULL (ADR-0131 D1), and the save guard
// (`assignment-rule-hooks.ts`) refuses a row that would land in no
// organization. A row that names its organization is stored under that
// name, as before; the stamp fills only an absent one.
fields: {
// Non-null: a stored rule always belongs to one organization. A rule that
// reaches every organization is a DECLARED rule, never a row here.
organization_id: Field.lookup('sys_organization', {
label: 'Organization',
required: true,
group: 'System',
description: 'The organization this rule belongs to.',
}),

name: Field.text({
label: 'Name',
required: true,
Expand Down Expand Up @@ -184,6 +192,7 @@ export const SysAssignmentRule = ObjectSchema.create({
indexes: [
{ fields: ['object_name', 'active'] },
{ fields: ['name'], unique: 'organization' },
{ fields: ['organization_id'] },
// No `organization_id` entry: the column is the platform's, and so is its
// index, provisioned with it on a multi-tenant deployment, as on `sys_queue`.
],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* An assignment rule created by an organization's administrator, with no
* organization in the body, lands in that administrator's organization (the
* Setup form's create). Before the fix the object declared its own
* `organization_id`, `required`, so the record validator refused the write
* ("Organization is required") before the platform could stamp the column,
* and Setup, whose form has no organization input, could not create a rule.
*
* ## Why a real engine and driver
*
* The stamp is a chain, not a line: registration injects the platform's
* tenant column (`applySystemFields`), the validator leaves that column to the
* platform, and the SQL driver fills it from the write's organization
* (`injectTenantOnInsert`). A double proves none of that. So these cases run
* the shipped `sys_assignment_rule` and `sys_queue` definitions through a real
* `ObjectQL` over a real `SqlDriver` on better-sqlite3 `:memory:`, with the
* save guard bound, and read the stored rows straight off the driver. The
* engine's `insert` is the call the data API's create makes; the HTTP layer
* and plugin-security's tenant wall are not composed here.
*/

import { describe, it, expect, afterEach, vi } from 'vitest';
import { ObjectQL } from '@objectstack/objectql';
import { SqlDriver } from '@objectstack/driver-sql';
import type { ExecutionContext } from '@objectstack/spec/kernel';

import { SysAssignmentRule } from './sys-assignment-rule.object.js';
import { SysQueue } from './sys-queue.object.js';
import { SysQueueMember } from './sys-queue-member.object.js';
import { bindAssignmentRuleGuards } from '../assignment-rule-hooks.js';
import { OwnershipQueueService } from '../ownership-queue-service.js';

const ORG_A = 'org_a';
const ORG_B = 'org_b';
const TARGET = 'os39415_ticket';
/** The engine's ownership-queue slot (`@objectstack/objectql` assignment-rules, a `Symbol.for` key). */
const OWNERSHIP_QUEUE_SOURCE_SLOT = Symbol.for('objectstack.objectql.ownershipQueueSource');

const ORG_FIELDS = {
id: { type: 'text', name: 'id', label: 'Id', primary: true },
name: { type: 'text', name: 'name', label: 'Name' },
};

const SYSTEM: ExecutionContext = { isSystem: true, positions: [], permissions: [] } as unknown as ExecutionContext;

/** A signed-in administrator whose active organization is `organization`. */
const adminOf = (organization: string): ExecutionContext => ({
userId: `u_admin_${organization}`,
tenantId: organization,
positions: [],
permissions: [],
} as unknown as ExecutionContext);

/** The body the Setup form sends: every visible field, no organization. */
const setupBody = (name: string) => ({
name,
label: 'Route repairs',
object_name: TARGET,
recipient_type: 'queue',
recipient_id: 'repair',
strategy: 'round_robin',
});

const open: SqlDriver[] = [];
afterEach(async () => {
while (open.length) await open.pop()?.disconnect?.();
vi.unstubAllEnvs();
});

async function boot() {
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
open.push(driver);
// A walled deployment, read by the registry at construction: it provisions
// the tenant column's index on that posture.
vi.stubEnv('OS_TENANCY_POSTURE', 'isolated');
const ql = new ObjectQL();
ql.registerDriver(driver as never, true);
await ql.init();
ql.setTenancyPostureProvider(() => 'isolated');
// The real `sys_organization` carries no tenant column of its own.
ql.registerObject({ name: 'sys_organization', label: 'Organization', isSystem: true, systemFields: { tenant: false }, fields: ORG_FIELDS } as never);
ql.registerObject(SysQueue as never);
ql.registerObject(SysQueueMember as never);
ql.registerObject(SysAssignmentRule as never);
// An owned object, so it carries the ownership-queue column a rule routes by.
ql.registerObject({ name: TARGET, label: 'Ticket', fields: { subject: { type: 'text', name: 'subject', label: 'Subject' } } } as never);
const registered = (name: string) => ql.registry.getObject(name) as unknown as { fields: Record<string, unknown> };
await driver.initObjects(['sys_organization', 'sys_queue', 'sys_queue_member', 'sys_assignment_rule', TARGET].map(registered) as never);
for (const id of [ORG_A, ORG_B]) await driver.create('sys_organization', { id, name: id } as never);
bindAssignmentRuleGuards(ql as never);
// The ownership-queue service the engine's assignment seam resolves a
// queue target through, in the slot the ObjectQL plugin fills at boot.
const queues = new OwnershipQueueService({ engine: () => ql as never });
(ql as unknown as Record<symbol, unknown>)[OWNERSHIP_QUEUE_SOURCE_SLOT] = () => queues;
const storedRules = async () =>
((await driver.find('sys_assignment_rule', {} as never)) as Array<Record<string, unknown>>)
.map((r) => ({ name: r.name, organization_id: r.organization_id }));
return { ql, driver, registered, storedRules };
}

describe('sys_assignment_rule — a rule created with no organization is stamped with the caller\'s', () => {
it('an organization administrator\'s create with no organization_id is stored in that organization', async () => {
const { ql, storedRules } = await boot();

const created = await ql.insert('sys_assignment_rule', setupBody('route_repairs'), { context: adminOf(ORG_A) } as never);

expect((created as Record<string, unknown>).organization_id).toBe(ORG_A);
expect(await storedRules()).toEqual([{ name: 'route_repairs', organization_id: ORG_A }]);
});

it('each administrator\'s rule lands in their own organization', async () => {
const { ql, storedRules } = await boot();

await ql.insert('sys_assignment_rule', setupBody('route_a'), { context: adminOf(ORG_A) } as never);
await ql.insert('sys_assignment_rule', setupBody('route_b'), { context: adminOf(ORG_B) } as never);

expect(await storedRules()).toEqual([
{ name: 'route_a', organization_id: ORG_A },
{ name: 'route_b', organization_id: ORG_B },
]);
});

it('the rule rides the same platform tenant column as sys_queue', async () => {
const { registered } = await boot();

// One mechanism: the column `sys_queue` is stamped through, field for field.
expect(registered('sys_assignment_rule').fields.organization_id).toEqual(registered('sys_queue').fields.organization_id);
expect(registered('sys_assignment_rule').fields.organization_id).toMatchObject({ system: true, reference: 'sys_organization' });
// Its index is the platform's too, provisioned with the column.
const indexes = (registered('sys_assignment_rule') as { indexes?: Array<{ fields: string[] }> }).indexes ?? [];
expect(indexes.filter((i) => i.fields.length === 1 && i.fields[0] === 'organization_id')).toHaveLength(1);
});

it('a row that names its organization keeps it: the stamp fills only an absent one', async () => {
const { ql, storedRules } = await boot();

await ql.insert('sys_assignment_rule', { ...setupBody('route_seeded'), organization_id: ORG_B }, { context: SYSTEM } as never);

expect(await storedRules()).toEqual([{ name: 'route_seeded', organization_id: ORG_B }]);
});

it('non-null still holds: a create that lands in no organization is refused, naming organization_id, and stores nothing', async () => {
const { ql, storedRules } = await boot();
const noOrganization = { userId: 'u_orphan', positions: [], permissions: [] } as unknown as ExecutionContext;

const refusal = await ql.insert('sys_assignment_rule', setupBody('route_orphan'), { context: noOrganization } as never)
.then(() => null, (e: unknown) => e as { code?: string; fields?: Array<{ field: string; code: string }> });

expect(refusal).not.toBeNull();
expect(refusal!.code).toBe('VALIDATION_FAILED');
expect(refusal!.fields).toEqual(expect.arrayContaining([expect.objectContaining({ field: 'organization_id', code: 'required' })]));
expect(await storedRules()).toEqual([]);
});
});

describe('sys_assignment_rule — the stamped rule lists and routes in its organization', () => {
it('the created rule lists for its organization and routes that organization\'s new records, and no other\'s', async () => {
const { ql, driver } = await boot();
// The queue the Setup form's rule names, authored in the same organization a minute earlier.
await ql.insert('sys_queue', { name: 'repair', label: 'Repair crew' }, { context: adminOf(ORG_A) } as never);
await ql.insert('sys_assignment_rule', setupBody('route_repairs'), { context: adminOf(ORG_A) } as never);

const listed = (await ql.find('sys_assignment_rule', { where: { organization_id: ORG_A } } as never, { context: adminOf(ORG_A) } as never)) as Array<Record<string, unknown>>;
expect(listed.map((r) => [r.name, r.organization_id])).toEqual([['route_repairs', ORG_A]]);

await ql.insert(TARGET, { subject: 'Leaking tap' }, { context: adminOf(ORG_A) } as never);
await ql.insert(TARGET, { subject: 'Broken door' }, { context: adminOf(ORG_B) } as never);

const tickets = ((await driver.find(TARGET, {} as never)) as Array<Record<string, unknown>>)
.map((t) => ({ subject: t.subject, organization_id: t.organization_id, queue: t.queue ?? null }));
// The rule evaluated: organization A's ticket sits in the rule's queue (the
// queue has no members, so it parks there); organization B's is untouched.
expect(tickets).toEqual([
{ subject: 'Leaking tap', organization_id: ORG_A, queue: 'repair' },
{ subject: 'Broken door', organization_id: ORG_B, queue: null },
]);
});

it('an update by the rule\'s own administrator cannot move it to another organization: the value is dropped, the rule stays', async () => {
// The tenant column is the platform's, read-only to a non-system write, as
// on `sys_queue`. With the object's own declaration the same update moved
// the rule into organization B. (A supplied organization on an INSERT is
// not judged here: the security plugin's write wall refuses a foreign one
// on a walled deployment, reading the column by name, as before.)
const { ql, storedRules } = await boot();
const created = (await ql.insert('sys_assignment_rule', setupBody('route_kept'), { context: adminOf(ORG_A) } as never)) as Record<string, unknown>;

await ql.update('sys_assignment_rule', { id: created.id, organization_id: ORG_B }, { context: adminOf(ORG_A) } as never);

expect(await storedRules()).toEqual([{ name: 'route_kept', organization_id: ORG_A }]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -362,10 +362,6 @@ export const arObjects: NonNullable<TranslationData['objects']> = {
pluralLabel: "قواعد الإسناد",
description: "ترسل كل سجل جديد يطابق شرطًا إلى قائمة انتظار أو إلى شخص.",
fields: {
organization_id: {
label: "المؤسسة",
help: "المؤسسة التي تنتمي إليها هذه القاعدة."
},
name: {
label: "الاسم",
help: "يعرّف القاعدة. أحرف لاتينية صغيرة وأرقام وشرطات سفلية فقط، ولا يجوز أن يكون اسم قاعدة يوفرها تطبيق مثبّت."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -362,10 +362,6 @@ export const deObjects: NonNullable<TranslationData['objects']> = {
pluralLabel: "Zuweisungsregeln",
description: "Sendet jeden neuen Datensatz, der eine Bedingung erfüllt, an eine Warteschlange oder an eine Person.",
fields: {
organization_id: {
label: "Organisation",
help: "Die Organisation, zu der diese Regel gehört."
},
name: {
label: "Name",
help: "Kennzeichnet die Regel. Nur Kleinbuchstaben, Ziffern und Unterstriche, und nicht der Name einer Regel, die eine installierte App bereitstellt."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -362,10 +362,6 @@ export const enObjects: NonNullable<TranslationData['objects']> = {
pluralLabel: "Assignment Rules",
description: "Sends each new record that matches a condition to a queue or a person.",
fields: {
organization_id: {
label: "Organization",
help: "The organization this rule belongs to."
},
name: {
label: "Name",
help: "Identifies the rule. Lowercase letters, digits and underscores only, and not the name of a rule an installed app provides."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -362,10 +362,6 @@ export const esESObjects: NonNullable<TranslationData['objects']> = {
pluralLabel: "Reglas de asignación",
description: "Envía cada registro nuevo que cumple una condición a una cola o a una persona.",
fields: {
organization_id: {
label: "Organización",
help: "La organización a la que pertenece esta regla."
},
name: {
label: "Nombre",
help: "Identifica la regla. Solo letras minúsculas, dígitos y guiones bajos, y no puede ser el nombre de una regla que proporcione una aplicación instalada."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -362,10 +362,6 @@ export const frObjects: NonNullable<TranslationData['objects']> = {
pluralLabel: "Règles d’attribution",
description: "Envoie chaque nouvel enregistrement qui remplit une condition à une file d’attente ou à une personne.",
fields: {
organization_id: {
label: "Organisation",
help: "L’organisation à laquelle appartient cette règle."
},
name: {
label: "Nom",
help: "Identifie la règle. Lettres minuscules, chiffres et traits de soulignement uniquement, et pas le nom d’une règle fournie par une application installée."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -362,10 +362,6 @@ export const jaJPObjects: NonNullable<TranslationData['objects']> = {
pluralLabel: "割り当てルール",
description: "条件に一致する新しいレコードを、キューまたは特定の人に送ります。",
fields: {
organization_id: {
label: "組織",
help: "このルールが属する組織。"
},
name: {
label: "名前",
help: "ルールを識別します。小文字、数字、アンダースコアのみ使用でき、インストール済みアプリが提供するルールと同じ名前は使えません。"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -362,10 +362,6 @@ export const koObjects: NonNullable<TranslationData['objects']> = {
pluralLabel: "배정 규칙",
description: "조건에 맞는 각 새 레코드를 대기열 또는 한 사람에게 보냅니다.",
fields: {
organization_id: {
label: "조직",
help: "이 규칙이 속한 조직입니다."
},
name: {
label: "이름",
help: "규칙을 식별합니다. 영문 소문자, 숫자, 밑줄만 쓸 수 있으며, 설치된 앱이 제공하는 규칙의 이름은 쓸 수 없습니다."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -362,10 +362,6 @@ export const ptBRObjects: NonNullable<TranslationData['objects']> = {
pluralLabel: "Regras de atribuição",
description: "Envia cada novo registro que atende a uma condição para uma fila ou para uma pessoa.",
fields: {
organization_id: {
label: "Organização",
help: "A organização à qual esta regra pertence."
},
name: {
label: "Nome",
help: "Identifica a regra. Apenas letras minúsculas, dígitos e sublinhados, e não pode ser o nome de uma regra fornecida por um aplicativo instalado."
Expand Down
Loading
Loading