diff --git a/.changeset/39415-assignment-rule-organization-stamp.md b/.changeset/39415-assignment-rule-organization-stamp.md new file mode 100644 index 00000000000..83eaf1400c7 --- /dev/null +++ b/.changeset/39415-assignment-rule-organization-stamp.md @@ -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. diff --git a/packages/plugins/plugin-sharing/src/objects/sys-assignment-rule.object.ts b/packages/plugins/plugin-sharing/src/objects/sys-assignment-rule.object.ts index de30fa6c441..e3845bcdcbe 100644 --- a/packages/plugins/plugin-sharing/src/objects/sys-assignment-rule.object.ts +++ b/packages/plugins/plugin-sharing/src/objects/sys-assignment-rule.object.ts @@ -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 @@ -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, @@ -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`. ], }); diff --git a/packages/plugins/plugin-sharing/src/objects/sys-assignment-rule.organization-stamp-39415.test.ts b/packages/plugins/plugin-sharing/src/objects/sys-assignment-rule.organization-stamp-39415.test.ts new file mode 100644 index 00000000000..11e1ea1ca66 --- /dev/null +++ b/packages/plugins/plugin-sharing/src/objects/sys-assignment-rule.organization-stamp-39415.test.ts @@ -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 }; + 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)[OWNERSHIP_QUEUE_SOURCE_SLOT] = () => queues; + const storedRules = async () => + ((await driver.find('sys_assignment_rule', {} as never)) as Array>) + .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).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>; + 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>) + .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; + + 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 }]); + }); +}); diff --git a/packages/plugins/plugin-sharing/src/translations/ar.objects.generated.ts b/packages/plugins/plugin-sharing/src/translations/ar.objects.generated.ts index 08896bf6724..d078f319dfe 100644 --- a/packages/plugins/plugin-sharing/src/translations/ar.objects.generated.ts +++ b/packages/plugins/plugin-sharing/src/translations/ar.objects.generated.ts @@ -362,10 +362,6 @@ export const arObjects: NonNullable = { pluralLabel: "قواعد الإسناد", description: "ترسل كل سجل جديد يطابق شرطًا إلى قائمة انتظار أو إلى شخص.", fields: { - organization_id: { - label: "المؤسسة", - help: "المؤسسة التي تنتمي إليها هذه القاعدة." - }, name: { label: "الاسم", help: "يعرّف القاعدة. أحرف لاتينية صغيرة وأرقام وشرطات سفلية فقط، ولا يجوز أن يكون اسم قاعدة يوفرها تطبيق مثبّت." diff --git a/packages/plugins/plugin-sharing/src/translations/de.objects.generated.ts b/packages/plugins/plugin-sharing/src/translations/de.objects.generated.ts index 1bd780da838..c8e6fa1dd62 100644 --- a/packages/plugins/plugin-sharing/src/translations/de.objects.generated.ts +++ b/packages/plugins/plugin-sharing/src/translations/de.objects.generated.ts @@ -362,10 +362,6 @@ export const deObjects: NonNullable = { 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." diff --git a/packages/plugins/plugin-sharing/src/translations/en.objects.generated.ts b/packages/plugins/plugin-sharing/src/translations/en.objects.generated.ts index de1b11d0dda..fafaf1e5a0d 100644 --- a/packages/plugins/plugin-sharing/src/translations/en.objects.generated.ts +++ b/packages/plugins/plugin-sharing/src/translations/en.objects.generated.ts @@ -362,10 +362,6 @@ export const enObjects: NonNullable = { 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." diff --git a/packages/plugins/plugin-sharing/src/translations/es-ES.objects.generated.ts b/packages/plugins/plugin-sharing/src/translations/es-ES.objects.generated.ts index 1ee0f9ea5a2..5e9eeccfc25 100644 --- a/packages/plugins/plugin-sharing/src/translations/es-ES.objects.generated.ts +++ b/packages/plugins/plugin-sharing/src/translations/es-ES.objects.generated.ts @@ -362,10 +362,6 @@ export const esESObjects: NonNullable = { 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." diff --git a/packages/plugins/plugin-sharing/src/translations/fr.objects.generated.ts b/packages/plugins/plugin-sharing/src/translations/fr.objects.generated.ts index a380440cf81..5de4467c1d2 100644 --- a/packages/plugins/plugin-sharing/src/translations/fr.objects.generated.ts +++ b/packages/plugins/plugin-sharing/src/translations/fr.objects.generated.ts @@ -362,10 +362,6 @@ export const frObjects: NonNullable = { 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." diff --git a/packages/plugins/plugin-sharing/src/translations/ja-JP.objects.generated.ts b/packages/plugins/plugin-sharing/src/translations/ja-JP.objects.generated.ts index 933dbd13734..be679a922a5 100644 --- a/packages/plugins/plugin-sharing/src/translations/ja-JP.objects.generated.ts +++ b/packages/plugins/plugin-sharing/src/translations/ja-JP.objects.generated.ts @@ -362,10 +362,6 @@ export const jaJPObjects: NonNullable = { pluralLabel: "割り当てルール", description: "条件に一致する新しいレコードを、キューまたは特定の人に送ります。", fields: { - organization_id: { - label: "組織", - help: "このルールが属する組織。" - }, name: { label: "名前", help: "ルールを識別します。小文字、数字、アンダースコアのみ使用でき、インストール済みアプリが提供するルールと同じ名前は使えません。" diff --git a/packages/plugins/plugin-sharing/src/translations/ko.objects.generated.ts b/packages/plugins/plugin-sharing/src/translations/ko.objects.generated.ts index a26879bcd0b..949630e0d10 100644 --- a/packages/plugins/plugin-sharing/src/translations/ko.objects.generated.ts +++ b/packages/plugins/plugin-sharing/src/translations/ko.objects.generated.ts @@ -362,10 +362,6 @@ export const koObjects: NonNullable = { pluralLabel: "배정 규칙", description: "조건에 맞는 각 새 레코드를 대기열 또는 한 사람에게 보냅니다.", fields: { - organization_id: { - label: "조직", - help: "이 규칙이 속한 조직입니다." - }, name: { label: "이름", help: "규칙을 식별합니다. 영문 소문자, 숫자, 밑줄만 쓸 수 있으며, 설치된 앱이 제공하는 규칙의 이름은 쓸 수 없습니다." diff --git a/packages/plugins/plugin-sharing/src/translations/pt-BR.objects.generated.ts b/packages/plugins/plugin-sharing/src/translations/pt-BR.objects.generated.ts index 6fa48ca6248..ed5c738ec7e 100644 --- a/packages/plugins/plugin-sharing/src/translations/pt-BR.objects.generated.ts +++ b/packages/plugins/plugin-sharing/src/translations/pt-BR.objects.generated.ts @@ -362,10 +362,6 @@ export const ptBRObjects: NonNullable = { 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." diff --git a/packages/plugins/plugin-sharing/src/translations/ru.objects.generated.ts b/packages/plugins/plugin-sharing/src/translations/ru.objects.generated.ts index 2a2f5a74376..f236f619b0c 100644 --- a/packages/plugins/plugin-sharing/src/translations/ru.objects.generated.ts +++ b/packages/plugins/plugin-sharing/src/translations/ru.objects.generated.ts @@ -362,10 +362,6 @@ export const ruObjects: NonNullable = { pluralLabel: "Правила назначения", description: "Отправляет каждую новую запись, удовлетворяющую условию, в очередь или конкретному человеку.", fields: { - organization_id: { - label: "Организация", - help: "Организация, к которой относится это правило." - }, name: { label: "Имя", help: "Идентифицирует правило. Только строчные латинские буквы, цифры и подчёркивания; имя не должно совпадать с именем правила, которое предоставляет установленное приложение." diff --git a/packages/plugins/plugin-sharing/src/translations/zh-CN.objects.generated.ts b/packages/plugins/plugin-sharing/src/translations/zh-CN.objects.generated.ts index 0c395858e3b..cddb17ca776 100644 --- a/packages/plugins/plugin-sharing/src/translations/zh-CN.objects.generated.ts +++ b/packages/plugins/plugin-sharing/src/translations/zh-CN.objects.generated.ts @@ -362,10 +362,6 @@ export const zhCNObjects: NonNullable = { pluralLabel: "分配规则", description: "将每条符合条件的新记录发送到一个队列或一个人。", fields: { - organization_id: { - label: "组织", - help: "该规则所属的组织。" - }, name: { label: "名称", help: "标识该规则。只能使用小写字母、数字和下划线,且不能与已安装应用提供的规则同名。" diff --git a/packages/plugins/plugin-sharing/src/translations/zh-Hant.objects.generated.ts b/packages/plugins/plugin-sharing/src/translations/zh-Hant.objects.generated.ts index 22805ec1df8..c12008a8ec1 100644 --- a/packages/plugins/plugin-sharing/src/translations/zh-Hant.objects.generated.ts +++ b/packages/plugins/plugin-sharing/src/translations/zh-Hant.objects.generated.ts @@ -362,10 +362,6 @@ export const zhHantObjects: NonNullable = { pluralLabel: "指派規則", description: "將每筆符合條件的新記錄傳送到一個佇列或一個人。", fields: { - organization_id: { - label: "組織", - help: "此規則所屬的組織。" - }, name: { label: "名稱", help: "識別此規則。只能使用小寫字母、數字和底線,且不能與已安裝應用程式提供的規則同名。"