Skip to content

Commit a4ed495

Browse files
committed
fix(core): a change of owner whose read-back leaves the caller's scope answers as moved
The engine refuses a missing row itself, before the write, and documents a null read-back after a by-id update as a write that landed and moved the row out of the caller's scope. Change Owner read that null as not found: the single door answered 404 and told nobody, the bulk door listed the row as failed, and a cascaded child counted as refused. The write's answer is no longer read for existence; the test doubles now throw RECORD_NOT_FOUND for a missing row, as the engine does. Claude-Session: https://claude.ai/code/session_011y7As8fiqghPfkY5FTbE3X Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 4af32b9 commit a4ed495

3 files changed

Lines changed: 105 additions & 24 deletions

File tree

‎packages/core/src/security/change-record-owner.test.ts‎

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
type ChangeOwnerEngine,
1616
} from './change-record-owner.js';
1717
import { USER_WORK_TRANSFER_ROW_CAP, UserWorkTransferRefusal } from './user-assigned-work.js';
18+
import { recordNotFoundError } from '../utils/record-not-found.js';
1819

1920
type Row = Record<string, any>;
2021

@@ -50,7 +51,14 @@ const CALLER = { userId: 'u_manager', tenantId: 'org_1' };
5051
* without, answering the stored row; refused before any write, as
5152
* `ERR_READONLY_FIELD_REJECTED`, under `strictReadonlyWrites`.
5253
*/
53-
function fakeEngine(opts: { refuse?: (id: string) => unknown; hiddenUsers?: string[]; locked?: (row: Row) => string[]; disabledPackageObjects?: string[] } = {}) {
54+
function fakeEngine(opts: {
55+
refuse?: (id: string) => unknown;
56+
hiddenUsers?: string[];
57+
locked?: (row: Row) => string[];
58+
disabledPackageObjects?: string[];
59+
/** 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. */
60+
leavesScope?: (object: string, id: string) => boolean;
61+
} = {}) {
5462
/** Per update call, in order: whether it passed `strictReadonlyWrites: true`. */
5563
const strictWrites: boolean[] = [];
5664
const tables: Record<string, Row[]> = {
@@ -99,14 +107,17 @@ function fakeEngine(opts: { refuse?: (id: string) => unknown; hiddenUsers?: stri
99107
calls.push({ op: 'update', object, data, where: o?.where, context: o?.context });
100108
strictWrites.push(o?.strictReadonlyWrites === true);
101109
const row = (tables[object] ?? []).find((r) => r.id === o?.where?.id);
102-
if (!row) return null;
110+
// The engine's not-found gate: a by-id update reads the row first and
111+
// throws before the write when the caller cannot reach it (`engine-update.ts`).
112+
if (!row) throw recordNotFoundError(object, String(o?.where?.id), o?.context as Parameters<typeof recordNotFoundError>[2]);
103113
const refusal = opts.refuse?.(row.id);
104114
if (refusal) throw refusal;
105115
const lockedKeys = (opts.locked?.(row) ?? []).filter((k) => Object.prototype.hasOwnProperty.call(data, k));
106116
if (lockedKeys.length > 0 && o?.strictReadonlyWrites === true) throw readonlyRejected(object, lockedKeys);
107117
const kept = Object.fromEntries(Object.entries(data).filter(([k]) => !lockedKeys.includes(k)));
108118
Object.assign(row, kept);
109-
return row;
119+
// A write that took the row out of the caller's scope reads back nothing, though it landed.
120+
return opts.leavesScope?.(object, row.id) === true ? null : row;
110121
},
111122
};
112123
return engine;
@@ -282,6 +293,50 @@ describe('[#35402] changeRecordsOwner — the bulk form', () => {
282293
});
283294
});
284295

296+
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"', () => {
297+
// Every row of `lead` reads back `null` once written: the move took it out of the caller's scope.
298+
const scoped = () => fakeEngine({ leavesScope: (object) => object === 'lead' });
299+
300+
it('single: answers the move and tells the new owner', async () => {
301+
const engine = scoped();
302+
const messaging = { emit: vi.fn(async () => SENT) };
303+
const result = await changeRecordOwner(engine, 'lead', 'l1', { ownerId: 'u_next' }, CALLER, { notify: true, messaging });
304+
expect(result).toEqual({ object: 'lead', id: 'l1', ownerId: 'u_next', notified: true });
305+
expect(engine.tables.lead[0]!.owner_id).toBe('u_next');
306+
expect(messaging.emit).toHaveBeenCalledTimes(1);
307+
});
308+
309+
it('bulk: the row counts under updated, none under failed, and the notice names it', async () => {
310+
const engine = scoped();
311+
const messaging = { emit: vi.fn(async () => SENT) };
312+
const report = await changeRecordsOwner(engine, 'lead', ['l1'], { ownerId: 'u_next' }, CALLER, { notify: true, messaging });
313+
expect(report).toMatchObject({ updated: 1, failed: 0, failures: [], notified: true });
314+
expect((messaging.emit.mock.calls[0] as any[])[0].payload.recordIds).toEqual(['l1']);
315+
});
316+
317+
it('a queue target whose read-back is null moved too', async () => {
318+
const result = await changeRecordOwner(scoped(), 'lead', 'l1', { queue: 'triage' }, CALLER);
319+
expect(result).toEqual({ object: 'lead', id: 'l1', ownerId: null, queue: 'triage', notified: false });
320+
});
321+
322+
it('a cascade still runs from a moved record, and a child whose read-back is null counts as moved', async () => {
323+
const engine = fakeEngine({ leavesScope: () => true });
324+
const result = await changeRecordOwner(engine, 'lead', 'l1', { ownerId: 'u_next' }, CALLER, {
325+
cascade: [{ object: 'lead_task', field: 'lead' }],
326+
});
327+
expect(result.cascade).toEqual([{ object: 'lead_task', field: 'lead', updated: 2, failed: 0, failures: [], remaining: 0 }]);
328+
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']]);
329+
});
330+
331+
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 () => {
332+
const single = await refusalOf(changeRecordOwner(scoped(), 'lead', 'l9', { ownerId: 'u_next' }, CALLER));
333+
expect({ code: single.code, status: single.status }).toEqual({ code: 'RECORD_NOT_FOUND', status: 404 });
334+
const report = await changeRecordsOwner(scoped(), 'lead', ['l1', 'l9'], { ownerId: 'u_next' }, CALLER);
335+
expect(report).toMatchObject({ updated: 1, failed: 1 });
336+
expect(report.failures.map((f) => [f.id, f.code])).toEqual([['l9', 'RECORD_NOT_FOUND']]);
337+
});
338+
});
339+
285340
describe('a readonlyWhen lock that holds: the answer is what was saved, not what was asked', () => {
286341
const closed = (engine: ReturnType<typeof fakeEngine>, ids: string[]) => {
287342
for (const r of engine.tables.lead) if (ids.includes(r.id)) r.status = 'closed';

‎packages/core/src/security/change-record-owner.ts‎

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,6 @@ import {
100100
import { SystemFieldName } from '@objectstack/spec/system';
101101
import { objectNotFoundError } from '../utils/object-not-found.js';
102102
import { objectPackageDisabledError } from '../utils/object-package-disabled.js';
103-
import { recordNotFoundError } from '../utils/record-not-found.js';
104103
import {
105104
assertAssignableUser,
106105
failureOf,
@@ -159,11 +158,24 @@ function lockedOwnerRefusal(err: unknown, object: string, id: string): Error | u
159158
/**
160159
* One record's owner write: a by-id update under the caller's context with
161160
* {@link OWNER_WRITE_OPTIONS}, a locked owner or queue answered as
162-
* {@link lockedOwnerRefusal}. Answers what the engine answers.
161+
* {@link lockedOwnerRefusal}. Resolves once the write landed; any other
162+
* outcome is a throw.
163+
*
164+
* The engine's answer is never read as "not found". A by-id update reads the
165+
* row as the caller BEFORE it writes and throws `404 RECORD_NOT_FOUND` itself
166+
* when the caller cannot reach it (`engine-update.ts`, the not-found gate),
167+
* so a call that returns wrote the row. What it returns is the driver's
168+
* post-write read-back, and that is `null` for a write that landed: a change
169+
* of owner that moves the row out of the caller's own row scope (handing a
170+
* record away under an owner-scoped read) reads back nothing, the case the
171+
* engine names when it explains why it asks existence before the write. A
172+
* driver that answers the write with nothing at all wrote it too. Reading
173+
* either as "not found" would answer 404, list the row as failed and tell
174+
* nobody, for a record that moved.
163175
*/
164-
async function writeOwner(engine: ChangeOwnerEngine, object: string, id: string, changeSet: AnyRec, context: unknown): Promise<unknown> {
176+
async function writeOwner(engine: ChangeOwnerEngine, object: string, id: string, changeSet: AnyRec, context: unknown): Promise<void> {
165177
try {
166-
return await engine.update(object, changeSet, { where: { id }, context, ...OWNER_WRITE_OPTIONS });
178+
await engine.update(object, changeSet, { where: { id }, context, ...OWNER_WRITE_OPTIONS });
167179
} catch (err) {
168180
throw lockedOwnerRefusal(err, object, id) ?? err;
169181
}
@@ -632,10 +644,7 @@ async function runCascade(
632644
// The parent's own owner write, so a child whose `owner_id` is locked
633645
// on that row (read-only, or a `readonlyWhen` that holds) is refused
634646
// `403 FIELD_NOT_ACCESSIBLE` and listed here, never counted as moved.
635-
const written = await writeOwner(engine, rel.object, String(childId), { [SystemFieldName.OWNER_ID]: newOwner }, context);
636-
if (written === null || written === undefined || written === 0) {
637-
throw recordNotFoundError(rel.object, String(childId), context as Parameters<typeof recordNotFoundError>[2]);
638-
}
647+
await writeOwner(engine, rel.object, String(childId), { [SystemFieldName.OWNER_ID]: newOwner }, context);
639648
outcome.updated += 1;
640649
} catch (err) {
641650
outcome.failed += 1;
@@ -665,8 +674,10 @@ async function runCascade(
665674
* refusal for a row the caller may not move (the route answers it as the
666675
* `/data` door answers the same throw), `403 FIELD_NOT_ACCESSIBLE` when a
667676
* `readonlyWhen` lock holds `owner_id` or `queue` on the row, `404
668-
* RECORD_NOT_FOUND` for a row the caller cannot reach, and the whole-call
669-
* refusals of {@link changeRecordsOwner}.
677+
* RECORD_NOT_FOUND` for a row the caller cannot reach (the engine's own
678+
* refusal, thrown before the write), and the whole-call refusals of
679+
* {@link changeRecordsOwner}. A row the move takes out of the caller's sight
680+
* moved, and is answered as moved ({@link writeOwner}).
670681
*/
671682
export async function changeRecordOwner(
672683
engine: ChangeOwnerEngine,
@@ -687,10 +698,7 @@ export async function changeRecordOwner(
687698
const relations = cascadeRelationsOf(engine, object, options.cascade, target);
688699
await assertTarget(engine, target, context);
689700
const before = relations.length > 0 ? await previousOwners(engine, object, [id], context) : undefined;
690-
const written = await writeOwner(engine, object, id, ownerChangeSet(target), context);
691-
if (written === null || written === undefined || written === 0) {
692-
throw recordNotFoundError(object, id, context as Parameters<typeof recordNotFoundError>[2]);
693-
}
701+
await writeOwner(engine, object, id, ownerChangeSet(target), context);
694702
const ownerId = target.ownerId ?? null;
695703
const cascade = before && ownerId !== null
696704
? await runCascade(engine, relations, [{ id, previousOwner: before.get(id) }], ownerId, context,
@@ -763,10 +771,7 @@ export async function changeRecordsOwner(
763771
const moved: string[] = [];
764772
for (const id of ids) {
765773
try {
766-
const written = await writeOwner(engine, object, id, { ...changeSet }, context);
767-
if (written === null || written === undefined || written === 0) {
768-
throw recordNotFoundError(object, id, context as Parameters<typeof recordNotFoundError>[2]);
769-
}
774+
await writeOwner(engine, object, id, { ...changeSet }, context);
770775
report.updated += 1;
771776
moved.push(id);
772777
} catch (err) {

‎packages/rest/src/change-owner-routes.test.ts‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { describe, it, expect, vi, afterEach } from 'vitest';
77
import { ObjectQL } from '@objectstack/objectql';
88
import { SqlDriver } from '@objectstack/driver-sql';
99
import { assertEngineUpdateDispatch } from '@objectstack/metadata-core';
10+
import { recordNotFoundError } from '@objectstack/core';
1011
import { OWNER_FIELD_DEF } from '@objectstack/spec/data';
1112
import { RestServer } from './rest-server';
1213
import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js';
@@ -45,7 +46,11 @@ const transferDenied = () => Object.assign(
4546
{ name: 'PermissionDeniedError', code: 'PERMISSION_DENIED', status: 403 },
4647
);
4748

48-
function mockEngine(refuse: (id: string) => unknown = () => undefined, disabledPackageObjects: string[] = []) {
49+
/**
50+
* `leavesScope`: the rows a write moves out of the caller's row scope — the
51+
* update lands and reads back `null`, as the engine answers one.
52+
*/
53+
function mockEngine(refuse: (id: string) => unknown = () => undefined, disabledPackageObjects: string[] = [], leavesScope: (id: string) => boolean = () => false) {
4954
const rows: Record<string, any>[] = [{ id: 'l1', owner_id: 'u_a' }, { id: 'l2', owner_id: 'u_b' }];
5055
const users = [{ id: 'u_next', banned: false }, { id: 'u_gone', banned: true }];
5156
const tasks: Record<string, any>[] = [{ id: 't1', lead: 'l1', owner_id: 'u_a' }, { id: 't2', lead: 'l1', owner_id: 'u_b' }];
@@ -68,11 +73,12 @@ function mockEngine(refuse: (id: string) => unknown = () => undefined, disabledP
6873
update: vi.fn(async (o: string, data: any, opts: any) => {
6974
assertEngineUpdateDispatch(data, opts);
7075
const row = tableOf(o).find((r) => r.id === opts.where.id);
71-
if (!row) return null;
76+
// The engine's not-found gate: read first, thrown before the write.
77+
if (!row) throw recordNotFoundError(o, String(opts.where.id), opts.context);
7278
const refusal = refuse(row.id);
7379
if (refusal) throw refusal;
7480
Object.assign(row, data);
75-
return row;
81+
return leavesScope(row.id) ? null : row;
7682
}),
7783
};
7884
}
@@ -168,6 +174,21 @@ describe('[#35402] POST /data/:object/:id/change-owner', () => {
168174
expect(engine.update).toHaveBeenCalledWith('lead', { owner_id: null, queue: 'triage' }, { where: { id: 'l1' }, context: CALLER, strictReadonlyWrites: true });
169175
});
170176

177+
it('a hand-away whose read-back is out of the caller\'s scope answers 200 and notifies, single and bulk', async () => {
178+
const messaging = { emit: vi.fn(async () => ({ delivered: 0, enqueued: 1 })) };
179+
const engine = mockEngine(undefined, [], () => true);
180+
const { single, bulk } = buildServer(engine, { messaging });
181+
const res = mockRes();
182+
await single!.handler(req({ object: 'lead', id: 'l1' }, { ownerId: 'u_next', notify: true }), res);
183+
expect(res.statusCode).toBe(200);
184+
expect(res.body.data).toEqual({ object: 'lead', id: 'l1', ownerId: 'u_next', notified: true });
185+
const many = mockRes();
186+
await bulk!.handler(req({ object: 'lead' }, { ids: ['l2'], ownerId: 'u_next' }), many);
187+
expect(many.statusCode).toBe(200);
188+
expect(many.body.data).toMatchObject({ updated: 1, failed: 0, failures: [] });
189+
expect(engine.rows.map((r) => r.owner_id)).toEqual(['u_next', 'u_next']);
190+
});
191+
171192
it('notify sends through the messaging service and says so', async () => {
172193
const messaging = { emit: vi.fn(async () => ({ delivered: 0, enqueued: 1 })) };
173194
const { single } = buildServer(mockEngine(), { messaging });

0 commit comments

Comments
 (0)