Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
13 changes: 13 additions & 0 deletions .changeset/36258-change-owner-readback-queue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@objectstack/core': patch
---

fix(core): Change Owner answers a hand-away that leaves the caller's view as moved, and refuses a queue target on an object with no queue column behind it

Clause-②: no
Metadata-protocol: none

- **A record handed away that the caller can no longer see moved.** When storage reads the record back under the caller's row access, a record handed to someone else reads back as nothing straight after the write. The write still landed, and the engine says so. Change Owner read that empty answer as "not found": the single door answered `404 RECORD_NOT_FOUND` and told nobody, the bulk door listed the record under `failures`, and a cascaded child counted as refused. Now the single door answers `200` and sends the notice when asked, the bulk door counts the record under `updated`, and the child counts as moved. A record the caller cannot reach is still answered `404 RECORD_NOT_FOUND`, by the engine, before anything is written. The built-in SQL storage keeps the record visible to the caller after the write, so it never showed this.
- **A queue target on an external object is refused.** A queue target needs the platform's `queue` column with storage behind it. Change Owner checked only for a field named `queue`. The platform registers that field on every object that has an owner, external objects included, where no column backs it, so an external object got a queue write in place of the `400 VALIDATION_ERROR` ("has no ownership queue column"). An object whose fields are registered as a list was refused with that sentence although it has the column. Now Change Owner uses the engine's own test for the column, `resolveInjectedColumnProvenance(def, 'queue') === 'injected-provisioned'`, so list-shaped and record-shaped `fields` get the same answer. A field the author declared and named `queue` is not the ownership queue. It does not let a queue target through, which matches the engine's assignment rules.

Nothing to migrate.
126 changes: 118 additions & 8 deletions packages/core/src/security/change-record-owner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import { describe, it, expect, vi } from 'vitest';
import { assertEngineUpdateDispatch } from '@objectstack/metadata-core';
import { OWNER_FIELD_DEF } from '@objectstack/spec/data';
import { OWNER_FIELD_DEF, QUEUE_FIELD_DEF } from '@objectstack/spec/data';
import {
CHANGE_OWNER_DISABLED,
CHANGE_OWNER_NOTIFICATION_TOPIC,
Expand All @@ -15,11 +15,10 @@ import {
type ChangeOwnerEngine,
} from './change-record-owner.js';
import { USER_WORK_TRANSFER_ROW_CAP, UserWorkTransferRefusal } from './user-assigned-work.js';
import { recordNotFoundError } from '../utils/record-not-found.js';

type Row = Record<string, any>;

const QUEUE_FIELD_DEF = { type: 'text', system: true };

// Registered shapes, as `applySystemFields` leaves them: the owner column and
// the queue column ride together on an owner-bearing object (ADR-0142 D3).
const lead = { name: 'lead', label: 'Lead', sharingModel: 'private', fields: { name: { type: 'text' }, owner_id: OWNER_FIELD_DEF, queue: QUEUE_FIELD_DEF } };
Expand All @@ -30,6 +29,19 @@ const orgOwned = { name: 'setting_row', ownership: 'org', fields: { name: { type
const managed = { name: 'auth_session', managedBy: 'better-auth', fields: { user_id: { type: 'lookup', reference: 'sys_user' } } };
const platform = { name: 'sys_team', fields: { name: { type: 'text' } } };
const noQueue = { name: 'memo', fields: { owner_id: OWNER_FIELD_DEF } };
// [#36262] An external (ADR-0015) object with a provable owner: the injection
// still registers `queue` beside `owner_id`, with no column behind it.
const extAccount = {
name: 'ext_account', label: 'Account', sharingModel: 'private', external: { remoteName: 'accounts' },
fields: { name: { type: 'text' }, owner_id: { type: 'lookup', reference: 'sys_user', label: 'Account owner' }, queue: QUEUE_FIELD_DEF },
};
// [#36262] The registered list shape of `fields`, the platform's queue column among them.
const listed = {
name: 'listed_lead', sharingModel: 'private',
fields: [{ name: 'name', type: 'text' }, { name: 'owner_id', ...OWNER_FIELD_DEF }, { name: 'queue', ...QUEUE_FIELD_DEF }],
};
// [#36262] A field the author named `queue`: theirs, not the ownership queue.
const authoredQueue = { name: 'ticket', sharingModel: 'private', fields: { owner_id: OWNER_FIELD_DEF, queue: { type: 'text', label: 'Support queue' } } };
// [#35315 phase 2] The cascade's children of `lead`: one declared cascade, one
// plain lookup, and — registered raw, past the parse that refuses it — a
// cascade on a controlled_by_parent detail, which is never a candidate.
Expand All @@ -38,7 +50,7 @@ const leadCall = { name: 'lead_call', sharingModel: 'private', fields: { lead: {
const leadLine = { name: 'lead_line', sharingModel: 'controlled_by_parent', fields: { lead: { type: 'master_detail', reference: 'lead', transferBehavior: 'cascade' }, owner_id: OWNER_FIELD_DEF } };

const SCHEMAS: Record<string, unknown> = Object.fromEntries(
[lead, pinned, line, lineOptedIn, orgOwned, managed, platform, noQueue, leadTask, leadCall, leadLine].map((o) => [o.name, o]),
[lead, pinned, line, lineOptedIn, orgOwned, managed, platform, noQueue, extAccount, listed, authoredQueue, leadTask, leadCall, leadLine].map((o) => [o.name, o]),
);

const CALLER = { userId: 'u_manager', tenantId: 'org_1' };
Expand All @@ -50,14 +62,24 @@ const CALLER = { userId: 'u_manager', tenantId: 'org_1' };
* without, answering the stored row; refused before any write, as
* `ERR_READONLY_FIELD_REJECTED`, under `strictReadonlyWrites`.
*/
function fakeEngine(opts: { refuse?: (id: string) => unknown; hiddenUsers?: string[]; locked?: (row: Row) => string[]; disabledPackageObjects?: string[] } = {}) {
function fakeEngine(opts: {
refuse?: (id: string) => unknown;
hiddenUsers?: string[];
locked?: (row: Row) => string[];
disabledPackageObjects?: string[];
/** Rows the write moves out of the caller's row scope: the update lands, and its read-back is `null`, as the engine answers one. */
leavesScope?: (object: string, id: string) => boolean;
} = {}) {
/** Per update call, in order: whether it passed `strictReadonlyWrites: true`. */
const strictWrites: boolean[] = [];
const tables: Record<string, Row[]> = {
sys_user: [{ id: 'u_next', banned: false }, { id: 'u_gone', banned: true }, { id: 'u_manager', banned: false }],
lead: [{ id: 'l1', owner_id: 'u_a' }, { id: 'l2', owner_id: 'u_b' }, { id: 'l3', owner_id: 'u_a' }],
contract_line: [{ id: 'c1', owner_id: 'u_a' }],
memo: [{ id: 'm1', owner_id: 'u_a' }],
ext_account: [{ id: 'x1', owner_id: 'u_a' }],
listed_lead: [{ id: 'd1', owner_id: 'u_a' }],
ticket: [{ id: 'k1', owner_id: 'u_a' }],
lead_task: [
{ id: 't1', lead: 'l1', owner_id: 'u_a' },
{ id: 't2', lead: 'l1', owner_id: 'u_b' },
Expand Down Expand Up @@ -99,14 +121,17 @@ function fakeEngine(opts: { refuse?: (id: string) => unknown; hiddenUsers?: stri
calls.push({ op: 'update', object, data, where: o?.where, context: o?.context });
strictWrites.push(o?.strictReadonlyWrites === true);
const row = (tables[object] ?? []).find((r) => r.id === o?.where?.id);
if (!row) return null;
// The engine's not-found gate: a by-id update reads the row first and
// throws before the write when the caller cannot reach it (`engine-update.ts`).
if (!row) throw recordNotFoundError(object, String(o?.where?.id), o?.context as Parameters<typeof recordNotFoundError>[2]);
const refusal = opts.refuse?.(row.id);
if (refusal) throw refusal;
const lockedKeys = (opts.locked?.(row) ?? []).filter((k) => Object.prototype.hasOwnProperty.call(data, k));
if (lockedKeys.length > 0 && o?.strictReadonlyWrites === true) throw readonlyRejected(object, lockedKeys);
const kept = Object.fromEntries(Object.entries(data).filter(([k]) => !lockedKeys.includes(k)));
Object.assign(row, kept);
return row;
// A write that took the row out of the caller's scope reads back nothing, though it landed.
return opts.leavesScope?.(object, row.id) === true ? null : row;
},
};
return engine;
Expand Down Expand Up @@ -188,7 +213,7 @@ describe('[#35402] changeRecordOwner — one record', () => {

it('a queue target on an object with no queue column is refused before any write', async () => {
const engine = fakeEngine();
const err = await refusalOf(changeRecordOwner(engine, 'memo', 'm1', { queue: 'triage' }, CALLER));
const err = await refusalOf(changeRecordOwner(engine, 'ext_account', 'x1', { queue: 'triage' }, CALLER));
expect(err).toBeInstanceOf(UserWorkTransferRefusal);
expect({ code: err.code, status: err.status }).toEqual({ code: 'VALIDATION_ERROR', status: 400 });
expect(engine.calls.some((c) => c.op === 'update')).toBe(false);
Expand Down Expand Up @@ -234,6 +259,47 @@ describe('[#35402] changeRecordOwner — one record', () => {
});
});

describe('[#36262] a queue target asks for the queue column with storage behind it, as the engine does', () => {
it('an external object with an owner, whose injected queue has no column, is refused 400 before any write: single and bulk', async () => {
const engine = fakeEngine();
const single = await refusalOf(changeRecordOwner(engine, 'ext_account', 'x1', { queue: 'triage' }, CALLER));
expect({ code: single.code, status: single.status }).toEqual({ code: 'VALIDATION_ERROR', status: 400 });
expect(single.message).toMatch(/^'ext_account' has no ownership queue column/);
const bulk = await refusalOf(changeRecordsOwner(engine, 'ext_account', ['x1'], { queue: 'triage' }, CALLER));
expect({ code: bulk.code, status: bulk.status }).toEqual({ code: 'VALIDATION_ERROR', status: 400 });
expect(engine.calls.some((c) => c.op === 'update')).toBe(false);
expect(engine.tables.ext_account[0]).toEqual({ id: 'x1', owner_id: 'u_a' });
});

it('the external object still takes a person target: only the queue column is missing', async () => {
const result = await changeRecordOwner(fakeEngine(), 'ext_account', 'x1', { ownerId: 'u_next' }, CALLER);
expect(result).toEqual({ object: 'ext_account', id: 'x1', ownerId: 'u_next', notified: false });
});

it('list-shaped fields with the platform\'s queue column are admitted, single and bulk', async () => {
const engine = fakeEngine();
const result = await changeRecordOwner(engine, 'listed_lead', 'd1', { queue: 'triage' }, CALLER);
expect(result).toEqual({ object: 'listed_lead', id: 'd1', ownerId: null, queue: 'triage', notified: false });
const report = await changeRecordsOwner(engine, 'listed_lead', ['d1'], { queue: 'triage' }, CALLER);
expect(report).toMatchObject({ updated: 1, failed: 0 });
});

it('control: a local object with the provisioned queue column is admitted, whether its document lists the column or the injection adds it', async () => {
for (const [object, id] of [['lead', 'l1'], ['memo', 'm1']] as const) {
const engine = fakeEngine();
const result = await changeRecordOwner(engine, object, id, { queue: 'triage' }, CALLER);
expect(result, object).toEqual({ object, id, ownerId: null, queue: 'triage', notified: false });
}
});

it('a field the author named queue is not the ownership queue: refused 400 before any write', async () => {
const engine = fakeEngine();
const err = await refusalOf(changeRecordOwner(engine, 'ticket', 'k1', { queue: 'triage' }, CALLER));
expect({ code: err.code, status: err.status }).toEqual({ code: 'VALIDATION_ERROR', status: 400 });
expect(engine.calls.some((c) => c.op === 'update')).toBe(false);
});
});

describe('[#35402] changeRecordsOwner — the bulk form', () => {
it('a mixed batch: one moves, one refused by the owner guard, one out of reach — every failure listed with its id', async () => {
const engine = fakeEngine({ refuse: (id) => (id === 'l2' ? transferDenied() : undefined) });
Expand Down Expand Up @@ -282,6 +348,50 @@ describe('[#35402] changeRecordsOwner — the bulk form', () => {
});
});

describe('a hand-away whose read-back is out of the caller\'s scope moved: the engine\'s null read-back is not "not found"', () => {
// Every row of `lead` reads back `null` once written: the move took it out of the caller's scope.
const scoped = () => fakeEngine({ leavesScope: (object) => object === 'lead' });

it('single: answers the move and tells the new owner', async () => {
const engine = scoped();
const messaging = { emit: vi.fn(async () => SENT) };
const result = await changeRecordOwner(engine, 'lead', 'l1', { ownerId: 'u_next' }, CALLER, { notify: true, messaging });
expect(result).toEqual({ object: 'lead', id: 'l1', ownerId: 'u_next', notified: true });
expect(engine.tables.lead[0]!.owner_id).toBe('u_next');
expect(messaging.emit).toHaveBeenCalledTimes(1);
});

it('bulk: the row counts under updated, none under failed, and the notice names it', async () => {
const engine = scoped();
const messaging = { emit: vi.fn(async () => SENT) };
const report = await changeRecordsOwner(engine, 'lead', ['l1'], { ownerId: 'u_next' }, CALLER, { notify: true, messaging });
expect(report).toMatchObject({ updated: 1, failed: 0, failures: [], notified: true });
expect((messaging.emit.mock.calls[0] as any[])[0].payload.recordIds).toEqual(['l1']);
});

it('a queue target whose read-back is null moved too', async () => {
const result = await changeRecordOwner(scoped(), 'lead', 'l1', { queue: 'triage' }, CALLER);
expect(result).toEqual({ object: 'lead', id: 'l1', ownerId: null, queue: 'triage', notified: false });
});

it('a cascade still runs from a moved record, and a child whose read-back is null counts as moved', async () => {
const engine = fakeEngine({ leavesScope: () => true });
const result = await changeRecordOwner(engine, 'lead', 'l1', { ownerId: 'u_next' }, CALLER, {
cascade: [{ object: 'lead_task', field: 'lead' }],
});
expect(result.cascade).toEqual([{ object: 'lead_task', field: 'lead', updated: 2, failed: 0, failures: [], remaining: 0 }]);
expect(engine.tables.lead_task.map((r) => [r.id, r.owner_id])).toEqual([['t1', 'u_next'], ['t2', 'u_b'], ['t3', 'u_next'], ['t4', 'u_b']]);
});

it('a row that is not there is the engine\'s own 404 RECORD_NOT_FOUND, thrown before the write: single refused, bulk lists it', async () => {
const single = await refusalOf(changeRecordOwner(scoped(), 'lead', 'l9', { ownerId: 'u_next' }, CALLER));
expect({ code: single.code, status: single.status }).toEqual({ code: 'RECORD_NOT_FOUND', status: 404 });
const report = await changeRecordsOwner(scoped(), 'lead', ['l1', 'l9'], { ownerId: 'u_next' }, CALLER);
expect(report).toMatchObject({ updated: 1, failed: 1 });
expect(report.failures.map((f) => [f.id, f.code])).toEqual([['l9', 'RECORD_NOT_FOUND']]);
});
});

describe('a readonlyWhen lock that holds: the answer is what was saved, not what was asked', () => {
const closed = (engine: ReturnType<typeof fakeEngine>, ids: string[]) => {
for (const r of engine.tables.lead) if (ids.includes(r.id)) r.status = 'closed';
Expand Down
Loading
Loading