Skip to content

Commit 09bab33

Browse files
committed
test: pin the banned-user refusal, the assigned-work count and the hand-over; add the SDK methods
Claude-Session: https://claude.ai/code/session_01Utp6CZavYYLh5k5r6jhgCF Co-authored-by: Claude <noreply@anthropic.com>
1 parent 01ab401 commit 09bab33

7 files changed

Lines changed: 684 additions & 6 deletions

File tree

‎packages/client/src/admin-surfaces.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,3 +127,24 @@ describe('client.security.suggestedBindings', () => {
127127
expect(result).toEqual({ suggestion: { id: 'sug/3', status: 'pending' } });
128128
});
129129
});
130+
131+
describe('client.security.assignedWork (#30205)', () => {
132+
it('count GETs the user-scoped route, encoding the id, and unwraps the summary', async () => {
133+
const summary = { userId: 'u/1', objects: [{ object: 'ticket', field: 'owner_id', count: 3, transferable: true }], total: 3, truncated: false, unreadable: [] };
134+
const { client, fetchMock } = createMockClient({ success: true, data: summary });
135+
const result = await client.security.assignedWork.count('u/1');
136+
expect(String(fetchMock.mock.calls[0][0])).toBe('http://localhost:3000/api/v1/security/users/u%2F1/assigned-work');
137+
expect(result).toEqual(summary);
138+
});
139+
140+
it('transfer POSTs the target and the optional object list', async () => {
141+
const report = { fromUserId: 'u_1', toUserId: 'u_2', objects: [], updated: 0, failed: 0, remaining: 0 };
142+
const { client, fetchMock } = createMockClient({ success: true, data: report });
143+
const result = await client.security.assignedWork.transfer('u_1', { toUserId: 'u_2', objects: ['ticket'] });
144+
const [url, init] = fetchMock.mock.calls[0];
145+
expect(String(url)).toBe('http://localhost:3000/api/v1/security/users/u_1/assigned-work/transfer');
146+
expect(init.method).toBe('POST');
147+
expect(JSON.parse(init.body)).toEqual({ toUserId: 'u_2', objects: ['ticket'] });
148+
expect(result).toEqual(report);
149+
});
150+
});

‎packages/client/src/index.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,34 @@ import { RealtimeAPI } from './realtime-api';
220220
*/
221221
export type ApiRouteType = keyof ApiRoutes;
222222

223+
/**
224+
* [#30205] `security.assignedWork.count`'s answer: per object and user field,
225+
* how many records hold the user, as the caller can read them.
226+
*/
227+
export interface UserAssignedWorkSummary {
228+
userId: string;
229+
objects: Array<{ object: string; field: string; count: number; transferable: boolean }>;
230+
total: number;
231+
truncated: boolean;
232+
unreadable: string[];
233+
}
234+
235+
/** [#30205] `security.assignedWork.transfer`'s answer: what moved, what failed, what remains. */
236+
export interface UserWorkTransferReport {
237+
fromUserId: string;
238+
toUserId: string;
239+
objects: Array<{
240+
object: string;
241+
field: string;
242+
updated: number;
243+
failed: number;
244+
failures: Array<{ id: string; code: string; message: string }>;
245+
}>;
246+
updated: number;
247+
failed: number;
248+
remaining: number;
249+
}
250+
223251
export interface ClientConfig {
224252
baseUrl: string;
225253
token?: string;
@@ -6465,6 +6493,45 @@ export class ObjectStackClient {
64656493
return this.unwrapResponse(res);
64666494
},
64676495
},
6496+
6497+
/**
6498+
* [#30205] A user's open work — what an administrator needs when they ban
6499+
* someone. Both calls run as the CALLER: the counts are what the caller
6500+
* can read, and each moved record is an ordinary update under the
6501+
* caller's permissions (sharing, validation and hooks apply). Neither
6502+
* touches the ban, which stays `POST /api/v1/auth/admin/ban-user`.
6503+
*/
6504+
assignedWork: {
6505+
/**
6506+
* Per object and user field (the owner field and every app user
6507+
* field), how many records hold `userId`. Objects the caller cannot
6508+
* read are named in `unreadable`; `truncated` says more fields exist
6509+
* than were counted.
6510+
*/
6511+
count: async (userId: string): Promise<UserAssignedWorkSummary> => {
6512+
const res = await this.fetch(
6513+
`${this.baseUrl}/api/v1/security/users/${encodeURIComponent(userId)}/assigned-work`,
6514+
);
6515+
return this.unwrapResponse<UserAssignedWorkSummary>(res);
6516+
},
6517+
6518+
/**
6519+
* Hand up to 500 of `userId`'s records to the active user `toUserId`
6520+
* (optionally only on `objects`), and answer what moved, what failed
6521+
* and how many remain; call again until `remaining` is 0. A banned or
6522+
* unknown `toUserId` is refused before anything moves.
6523+
*/
6524+
transfer: async (
6525+
userId: string,
6526+
request: { toUserId: string; objects?: string[] },
6527+
): Promise<UserWorkTransferReport> => {
6528+
const res = await this.fetch(
6529+
`${this.baseUrl}/api/v1/security/users/${encodeURIComponent(userId)}/assigned-work/transfer`,
6530+
{ method: 'POST', body: JSON.stringify(request) },
6531+
);
6532+
return this.unwrapResponse<UserWorkTransferReport>(res);
6533+
},
6534+
},
64686535
};
64696536

64706537
/**
Lines changed: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { describe, it, expect } from 'vitest';
4+
import {
5+
countUserAssignedWork,
6+
isUserBanInForce,
7+
transferUserAssignedWork,
8+
userAssignedWorkFields,
9+
UserWorkTransferRefusal,
10+
type UserWorkEngine,
11+
} from './user-assigned-work.js';
12+
13+
const NOW = Date.parse('2026-11-05T12:00:00Z');
14+
15+
describe('[#30205] isUserBanInForce', () => {
16+
it('a ban with no expiry, or one still ahead, is in force', () => {
17+
expect(isUserBanInForce({ banned: true }, NOW)).toBe(true);
18+
expect(isUserBanInForce({ banned: true, ban_expires: null }, NOW)).toBe(true);
19+
expect(isUserBanInForce({ banned: true, ban_expires: '2026-11-06T00:00:00Z' }, NOW)).toBe(true);
20+
expect(isUserBanInForce({ banned: true, ban_expires: new Date(NOW + 1000) }, NOW)).toBe(true);
21+
});
22+
23+
it('an expired ban, an unbanned user and a non-row are not', () => {
24+
expect(isUserBanInForce({ banned: true, ban_expires: '2026-11-04T00:00:00Z' }, NOW)).toBe(false);
25+
expect(isUserBanInForce({ banned: false }, NOW)).toBe(false);
26+
expect(isUserBanInForce({ banned: null }, NOW)).toBe(false);
27+
expect(isUserBanInForce({}, NOW)).toBe(false);
28+
expect(isUserBanInForce(null, NOW)).toBe(false);
29+
});
30+
31+
it('an expiry that does not parse cannot prove the ban lifted', () => {
32+
expect(isUserBanInForce({ banned: true, ban_expires: 'not a date' }, NOW)).toBe(true);
33+
});
34+
});
35+
36+
const ticket = {
37+
name: 'ticket',
38+
fields: {
39+
title: { type: 'text' },
40+
owner_id: { type: 'lookup', reference: 'sys_user' },
41+
assignee: { type: 'user' },
42+
watchers: { type: 'lookup', reference: 'sys_user', multiple: true },
43+
created_by: { type: 'lookup', reference: 'sys_user', readonly: true, system: true },
44+
account: { type: 'lookup', reference: 'account' },
45+
},
46+
};
47+
const account = { name: 'account', fields: { owner_id: { type: 'lookup', reference: 'sys_user' } } };
48+
const grant = { name: 'sys_user_permission_set', fields: { user_id: { type: 'lookup', reference: 'sys_user' } } };
49+
const managed = { name: 'auth_session', managedBy: 'better-auth', fields: { user_id: { type: 'lookup', reference: 'sys_user' } } };
50+
51+
describe('[#30205] userAssignedWorkFields', () => {
52+
it('counts the owner field and every app user field; leaves provenance, platform tables and managed objects out', () => {
53+
const { fields, truncated } = userAssignedWorkFields([ticket, account, grant, managed]);
54+
expect(truncated).toBe(false);
55+
expect(fields).toEqual([
56+
{ object: 'ticket', field: 'owner_id', multiple: false },
57+
{ object: 'ticket', field: 'assignee', multiple: false },
58+
{ object: 'ticket', field: 'watchers', multiple: true },
59+
{ object: 'account', field: 'owner_id', multiple: false },
60+
]);
61+
});
62+
63+
it('stops at the cap and says so', () => {
64+
const { fields, truncated } = userAssignedWorkFields([ticket, account], 2);
65+
expect(fields).toHaveLength(2);
66+
expect(truncated).toBe(true);
67+
});
68+
});
69+
70+
type Row = Record<string, any>;
71+
72+
/** An in-memory engine: equality and `$contains` filters, a per-object read/write refusal. */
73+
function fakeEngine(seed: Record<string, Row[]>, opts: { unreadable?: string[]; refuseUpdate?: (object: string, id: string) => boolean; disabled?: string[] } = {}) {
74+
const tables = new Map(Object.entries(seed).map(([k, rows]) => [k, rows.map((r) => ({ ...r }))]));
75+
const calls: Array<{ op: string; object: string; context: any; where?: any }> = [];
76+
const match = (row: Row, where: Record<string, any>) => Object.entries(where).every(([k, v]) =>
77+
v && typeof v === 'object' && '$contains' in v ? Array.isArray(row[k]) && row[k].includes(v.$contains) : row[k] === v);
78+
const guard = (object: string, context: any) => {
79+
if (opts.unreadable?.includes(object) && !context?.isSystem) throw Object.assign(new Error('denied'), { code: 'PERMISSION_DENIED' });
80+
};
81+
const engine: UserWorkEngine & { tables: typeof tables; calls: typeof calls } = {
82+
tables,
83+
calls,
84+
registry: { isObjectPackageDisabled: (name: string) => opts.disabled?.includes(name) ?? false },
85+
getConfigs: () => ({ ticket, account, grant, user: { name: 'sys_user', fields: {} } }),
86+
async count(object, q) {
87+
calls.push({ op: 'count', object, context: q?.context, where: q?.where });
88+
guard(object, q?.context);
89+
return (tables.get(object) ?? []).filter((r) => match(r, q?.where ?? {})).length;
90+
},
91+
async find(object, q) {
92+
calls.push({ op: 'find', object, context: q?.context, where: q?.where });
93+
guard(object, q?.context);
94+
const rows = (tables.get(object) ?? []).filter((r) => match(r, q?.where ?? {}));
95+
return typeof q?.limit === 'number' ? rows.slice(0, q.limit) : rows;
96+
},
97+
async update(object, data, o) {
98+
calls.push({ op: 'update', object, context: o?.context, where: o?.where });
99+
const row = (tables.get(object) ?? []).find((r) => match(r, o?.where ?? {}));
100+
if (!row) return null;
101+
if (opts.refuseUpdate?.(object, row.id)) throw Object.assign(new Error('Insufficient privileges'), { code: 'PERMISSION_DENIED' });
102+
Object.assign(row, data);
103+
return row;
104+
},
105+
};
106+
return engine;
107+
}
108+
109+
const CALLER = { userId: 'u_admin', tenantId: 'org_1' };
110+
111+
function seed(): Record<string, Row[]> {
112+
return {
113+
sys_user: [
114+
{ id: 'u_gone', banned: true },
115+
{ id: 'u_next', banned: false },
116+
{ id: 'u_also_banned', banned: true, ban_expires: null },
117+
],
118+
ticket: [
119+
{ id: 't1', owner_id: 'u_gone', assignee: 'u_gone', watchers: ['u_gone'] },
120+
{ id: 't2', owner_id: 'u_gone', assignee: 'u_x', watchers: [] },
121+
{ id: 't3', owner_id: 'u_x', assignee: 'u_gone', watchers: ['u_x', 'u_gone'] },
122+
],
123+
account: [{ id: 'a1', owner_id: 'u_gone' }, { id: 'a2', owner_id: 'u_x' }],
124+
};
125+
}
126+
127+
describe('[#30205] countUserAssignedWork', () => {
128+
it('answers per (object, field) counts as the caller, and the total', async () => {
129+
const engine = fakeEngine(seed());
130+
const summary = await countUserAssignedWork(engine, 'u_gone', CALLER);
131+
expect(summary).toEqual({
132+
userId: 'u_gone',
133+
objects: [
134+
{ object: 'ticket', field: 'owner_id', count: 2, transferable: true },
135+
{ object: 'ticket', field: 'assignee', count: 2, transferable: true },
136+
{ object: 'ticket', field: 'watchers', count: 2, transferable: false },
137+
{ object: 'account', field: 'owner_id', count: 1, transferable: true },
138+
],
139+
total: 7,
140+
truncated: false,
141+
unreadable: [],
142+
});
143+
// Every count ran under the caller's own context, never elevated.
144+
expect(engine.calls.every((c) => c.context === CALLER)).toBe(true);
145+
});
146+
147+
it('an object the caller cannot read is named, not counted as zero', async () => {
148+
const summary = await countUserAssignedWork(fakeEngine(seed(), { unreadable: ['account'] }), 'u_gone', CALLER);
149+
expect(summary.unreadable).toEqual(['account']);
150+
expect(summary.objects.map((o) => o.object)).not.toContain('account');
151+
});
152+
153+
it('a disabled package\'s object holds no work to count', async () => {
154+
const summary = await countUserAssignedWork(fakeEngine(seed(), { disabled: ['account'] }), 'u_gone', CALLER);
155+
expect(summary.objects.map((o) => o.object)).not.toContain('account');
156+
expect(summary.unreadable).toEqual([]);
157+
});
158+
});
159+
160+
describe('[#30205] transferUserAssignedWork', () => {
161+
it('moves every single-valued holding to the target as the caller, and answers what moved', async () => {
162+
const engine = fakeEngine(seed());
163+
const report = await transferUserAssignedWork(engine, 'u_gone', 'u_next', CALLER);
164+
expect(report).toEqual({
165+
fromUserId: 'u_gone',
166+
toUserId: 'u_next',
167+
objects: [
168+
{ object: 'ticket', field: 'owner_id', updated: 2, failed: 0, failures: [] },
169+
{ object: 'ticket', field: 'assignee', updated: 2, failed: 0, failures: [] },
170+
{ object: 'account', field: 'owner_id', updated: 1, failed: 0, failures: [] },
171+
],
172+
updated: 5,
173+
failed: 0,
174+
remaining: 0,
175+
});
176+
const t = engine.tables.get('ticket')!;
177+
expect(t.map((r) => [r.owner_id, r.assignee])).toEqual([['u_next', 'u_next'], ['u_next', 'u_x'], ['u_x', 'u_next']]);
178+
// A multi-valued field is never rewritten.
179+
expect(t[0].watchers).toEqual(['u_gone']);
180+
// Every write went through `update` under the caller's own context.
181+
const writes = engine.calls.filter((c) => c.op === 'update');
182+
expect(writes).toHaveLength(5);
183+
expect(writes.every((c) => c.context === CALLER)).toBe(true);
184+
});
185+
186+
it('reports a row the caller may not change as a failure and keeps going', async () => {
187+
const engine = fakeEngine(seed(), { refuseUpdate: (object, id) => object === 'ticket' && id === 't2' });
188+
const report = await transferUserAssignedWork(engine, 'u_gone', 'u_next', CALLER, { objects: ['ticket'] });
189+
expect(report.objects[0]).toEqual({
190+
object: 'ticket', field: 'owner_id', updated: 1, failed: 1,
191+
failures: [{ id: 't2', code: 'PERMISSION_DENIED', message: 'Insufficient privileges' }],
192+
});
193+
expect(report.failed).toBe(1);
194+
// The refused row still names the user, and `objects` kept account out.
195+
expect(report.remaining).toBe(1);
196+
expect(engine.tables.get('account')![0].owner_id).toBe('u_gone');
197+
});
198+
199+
it('moves at most the row cap per call and answers what remains', async () => {
200+
const engine = fakeEngine(seed());
201+
const first = await transferUserAssignedWork(engine, 'u_gone', 'u_next', CALLER, { rowCap: 3 });
202+
expect(first.updated).toBe(3);
203+
expect(first.remaining).toBe(2);
204+
const second = await transferUserAssignedWork(engine, 'u_gone', 'u_next', CALLER, { rowCap: 3 });
205+
expect(second.updated).toBe(2);
206+
expect(second.remaining).toBe(0);
207+
});
208+
209+
it('refuses a banned target, a missing one and the same user before any write', async () => {
210+
for (const [to, status, code, fieldCode] of [
211+
['u_also_banned', 400, 'VALIDATION_ERROR', 'reference_user_banned'],
212+
['u_nobody', 404, 'RESOURCE_NOT_FOUND', 'reference_not_found'],
213+
['u_gone', 400, 'VALIDATION_ERROR', undefined],
214+
] as const) {
215+
const engine = fakeEngine(seed());
216+
const err = await transferUserAssignedWork(engine, 'u_gone', to, CALLER).then(() => null, (e) => e);
217+
expect(err).toBeInstanceOf(UserWorkTransferRefusal);
218+
expect({ status: err.status, code: err.code, field: err.field?.code }).toEqual({ status, code, field: fieldCode });
219+
expect(engine.calls.filter((c) => c.op === 'update')).toHaveLength(0);
220+
}
221+
});
222+
223+
it('reads the target\'s ban state elevated inside the caller\'s tenant, even when the caller cannot read users', async () => {
224+
const engine = fakeEngine(seed(), { unreadable: ['sys_user'] });
225+
const err = await transferUserAssignedWork(engine, 'u_gone', 'u_also_banned', CALLER).then(() => null, (e) => e);
226+
expect(err?.field?.code).toBe('reference_user_banned');
227+
const read = engine.calls.find((c) => c.object === 'sys_user')!;
228+
expect(read.context).toEqual({ ...CALLER, isSystem: true });
229+
});
230+
});

0 commit comments

Comments
 (0)