|
| 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