|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | +// |
| 3 | +// [#22360] `assertSystemRowWriteGate` on a PACKAGE-provided `sys_position` row: |
| 4 | +// its definition is locked, its row state is not. |
| 5 | +// |
| 6 | +// The declared-position seeder stamps `managed_by: 'package'` on the row of a |
| 7 | +// position a code package holds, so this gate now protects that row. A package |
| 8 | +// position row is locked the way a packaged permission set is |
| 9 | +// (`permission-set-projection.ts`, #4669): a patch touching ONLY row state |
| 10 | +// (`active`, `is_default`) passes, because switching a package's position off, |
| 11 | +// or making it the default for new users, is not an edit of its definition. |
| 12 | +// Everything else stays refused with the gate's own code: a definition column |
| 13 | +// (`name`, `label`, `description`, `delegatable`), any other column, a delete |
| 14 | +// and the other lifecycle verbs. Platform (built-in) rows and `sys_capability` |
| 15 | +// get no carve-out. |
| 16 | +// |
| 17 | +// Each case runs one write through the plugin's REAL middleware over a store |
| 18 | +// double, so "admitted" means every gate after this one admitted it too. |
| 19 | + |
| 20 | +import { describe, it, expect, vi } from 'vitest'; |
| 21 | +import { SecurityPlugin } from './security-plugin.js'; |
| 22 | +import type { PermissionSet } from '@objectstack/spec/security'; |
| 23 | +import { assertEngineFindOnePredicate } from '@objectstack/metadata-core'; |
| 24 | + |
| 25 | +type Row = Record<string, unknown>; |
| 26 | + |
| 27 | +const POSITION_FIELDS = Object.fromEntries( |
| 28 | + ['id', 'name', 'label', 'description', 'active', 'is_default', 'delegatable', 'managed_by'].map((n) => [n, { name: n }]), |
| 29 | +); |
| 30 | +const SCHEMAS: Record<string, unknown> = { |
| 31 | + sys_position: { name: 'sys_position', fields: POSITION_FIELDS }, |
| 32 | + sys_capability: { name: 'sys_capability', fields: POSITION_FIELDS }, |
| 33 | +}; |
| 34 | + |
| 35 | +/** Plain CRUD on both asset objects — no wildcard, no `modifyAllRecords`. */ |
| 36 | +const ADMIN_SET: PermissionSet = { |
| 37 | + name: 'admin_set', |
| 38 | + label: 'Admin Set', |
| 39 | + objects: { |
| 40 | + sys_position: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }, |
| 41 | + sys_capability: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }, |
| 42 | + }, |
| 43 | +} as unknown as PermissionSet; |
| 44 | + |
| 45 | +const rows = (): Record<string, Row[]> => ({ |
| 46 | + sys_position: [ |
| 47 | + { id: 'pos_pkg_a', name: 'field_rep', label: 'Field Rep', managed_by: 'package', active: true }, |
| 48 | + { id: 'pos_pkg_b', name: 'auditor', label: 'Auditor', managed_by: 'package', active: true }, |
| 49 | + { id: 'pos_legacy', name: 'legacy_lead', label: 'Legacy Lead', managed_by: 'config', active: true }, |
| 50 | + { id: 'pos_platform', name: 'everyone', label: 'Everyone', managed_by: 'platform', active: true }, |
| 51 | + { id: 'pos_admin', name: 'regional_lead', label: 'Regional Lead', managed_by: 'admin', active: true }, |
| 52 | + ], |
| 53 | + sys_capability: [ |
| 54 | + { id: 'cap_pkg', name: 'pkg_cap', label: 'Package Capability', managed_by: 'package', active: true }, |
| 55 | + ], |
| 56 | +}); |
| 57 | + |
| 58 | +async function boot() { |
| 59 | + const store = rows(); |
| 60 | + const matches = (row: Row, where: any): boolean => { |
| 61 | + if (!where || typeof where !== 'object') return true; |
| 62 | + if (Array.isArray(where.$and) && !where.$and.every((w: any) => matches(row, w))) return false; |
| 63 | + if (Array.isArray(where.$or) && !where.$or.some((w: any) => matches(row, w))) return false; |
| 64 | + return Object.entries(where).every(([k, v]) => { |
| 65 | + if (k === '$and' || k === '$or') return true; |
| 66 | + if (v && typeof v === 'object' && Array.isArray((v as any).$in)) { |
| 67 | + return (v as any).$in.map(String).includes(String(row[k])); |
| 68 | + } |
| 69 | + return String(row[k]) === String(v); |
| 70 | + }); |
| 71 | + }; |
| 72 | + |
| 73 | + let middleware: any; |
| 74 | + const ql = { |
| 75 | + registerMiddleware: (mw: any) => { |
| 76 | + if (!middleware) middleware = mw; |
| 77 | + }, |
| 78 | + getSchema: (object: string) => SCHEMAS[object], |
| 79 | + find: vi.fn(async (object: string, o: any = {}) => (store[object] ?? []).filter((r) => matches(r, o?.where))), |
| 80 | + findOne: vi.fn(async (object: string, o: any = {}) => { |
| 81 | + assertEngineFindOnePredicate(object, o); |
| 82 | + return (store[object] ?? []).find((r) => matches(r, o?.where)) ?? null; |
| 83 | + }), |
| 84 | + }; |
| 85 | + const services: Record<string, unknown> = { |
| 86 | + manifest: { register: vi.fn() }, |
| 87 | + objectql: ql, |
| 88 | + metadata: { get: async (n: string) => SCHEMAS[n], list: async () => [ADMIN_SET] }, |
| 89 | + }; |
| 90 | + const ctx: any = { |
| 91 | + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, |
| 92 | + registerService: vi.fn(), |
| 93 | + getService: (name: string) => { |
| 94 | + if (!(name in services)) throw new Error(`service not registered: ${name}`); |
| 95 | + return services[name]; |
| 96 | + }, |
| 97 | + }; |
| 98 | + const plugin = new SecurityPlugin({ defaultPermissionSets: [ADMIN_SET], fallbackPermissionSet: ADMIN_SET.name }); |
| 99 | + await plugin.init(ctx); |
| 100 | + await plugin.start(ctx); |
| 101 | + |
| 102 | + /** One write through the real middleware: 'admitted', or the refusal's code + status + message. */ |
| 103 | + const write = async (opCtx: Record<string, unknown>): Promise<'admitted' | { code: unknown; status: unknown; message: string }> => { |
| 104 | + let admitted = false; |
| 105 | + try { |
| 106 | + await middleware( |
| 107 | + { options: {}, context: { userId: 'usr_admin', tenantId: 'org-1', positions: [], permissions: [] }, ...opCtx } as any, |
| 108 | + async () => { admitted = true; }, |
| 109 | + ); |
| 110 | + } catch (e: any) { |
| 111 | + return { code: e?.code, status: e?.status ?? e?.statusCode, message: String(e?.message ?? '') }; |
| 112 | + } |
| 113 | + if (!admitted) throw new Error('middleware resolved without calling next()'); |
| 114 | + return 'admitted'; |
| 115 | + }; |
| 116 | + return { write }; |
| 117 | +} |
| 118 | + |
| 119 | +const update = (object: string, data: unknown, where: Row = {}) => ({ object, operation: 'update', data, options: { where } }); |
| 120 | +const byId = (id: string, patch: Row) => update('sys_position', { id, ...patch }, { id }); |
| 121 | +const REFUSED = { code: 'PERMISSION_DENIED', status: 403 }; |
| 122 | + |
| 123 | +describe('[#22360] a package position row: row state switches, the definition stays locked', () => { |
| 124 | + it('a row-state-only patch passes: deactivate, activate, Set as Default, both together', async () => { |
| 125 | + const h = await boot(); |
| 126 | + expect(await h.write(byId('pos_pkg_a', { active: false }))).toBe('admitted'); |
| 127 | + expect(await h.write(byId('pos_pkg_a', { active: true }))).toBe('admitted'); |
| 128 | + expect(await h.write(byId('pos_pkg_a', { is_default: true }))).toBe('admitted'); |
| 129 | + expect(await h.write(byId('pos_pkg_a', { active: false, is_default: false }))).toBe('admitted'); |
| 130 | + // The id carried only by the filter, as the engine's by-id update spells it. |
| 131 | + expect(await h.write(update('sys_position', { active: false }, { id: 'pos_pkg_a' }))).toBe('admitted'); |
| 132 | + }); |
| 133 | + |
| 134 | + it('a definition column, any other column, or a mixed patch is refused with the gate\'s code', async () => { |
| 135 | + const h = await boot(); |
| 136 | + for (const patch of [ |
| 137 | + { label: 'Field Rep (edited)' }, |
| 138 | + { description: 'edited' }, |
| 139 | + { delegatable: true }, |
| 140 | + { name: 'field_rep_two' }, |
| 141 | + { active: false, label: 'Field Rep (edited)' }, |
| 142 | + { is_default: true, delegatable: true }, |
| 143 | + { active: false, notes: 'not a row-state column' }, |
| 144 | + ]) { |
| 145 | + const refused = await h.write(byId('pos_pkg_a', patch)); |
| 146 | + expect(refused, JSON.stringify(patch)).toMatchObject(REFUSED); |
| 147 | + expect((refused as any).message).toContain('provided by an application package'); |
| 148 | + } |
| 149 | + }); |
| 150 | + |
| 151 | + it('an empty patch admits nothing new: it is refused as before', async () => { |
| 152 | + const h = await boot(); |
| 153 | + expect(await h.write(byId('pos_pkg_a', {}))).toMatchObject(REFUSED); |
| 154 | + }); |
| 155 | + |
| 156 | + it('delete and the other lifecycle verbs stay refused', async () => { |
| 157 | + const h = await boot(); |
| 158 | + for (const operation of ['delete', 'transfer', 'restore', 'purge']) { |
| 159 | + const refused = await h.write({ object: 'sys_position', operation, options: { where: { id: 'pos_pkg_a' } } }); |
| 160 | + expect(refused, operation).toMatchObject(REFUSED); |
| 161 | + } |
| 162 | + }); |
| 163 | + |
| 164 | + it('the legacy `config` spelling of package provenance answers as its canonical twin', async () => { |
| 165 | + const h = await boot(); |
| 166 | + expect(await h.write(byId('pos_legacy', { active: false }))).toBe('admitted'); |
| 167 | + expect(await h.write(byId('pos_legacy', { label: 'edited' }))).toMatchObject(REFUSED); |
| 168 | + }); |
| 169 | + |
| 170 | + it('control: a built-in\'s bare { active } patch stays refused', async () => { |
| 171 | + const h = await boot(); |
| 172 | + const refused = await h.write(byId('pos_platform', { active: false })); |
| 173 | + expect(refused).toMatchObject(REFUSED); |
| 174 | + expect((refused as any).message).toContain('provided by the platform'); |
| 175 | + expect(await h.write(byId('pos_platform', { is_default: true }))).toMatchObject(REFUSED); |
| 176 | + }); |
| 177 | + |
| 178 | + it('control: sys_capability gets no carve-out', async () => { |
| 179 | + const h = await boot(); |
| 180 | + expect(await h.write(update('sys_capability', { id: 'cap_pkg', active: false }, { id: 'cap_pkg' }))).toMatchObject(REFUSED); |
| 181 | + }); |
| 182 | + |
| 183 | + it('control: an administrator-authored position stays fully editable', async () => { |
| 184 | + const h = await boot(); |
| 185 | + expect(await h.write(byId('pos_admin', { label: 'Regional Lead (edited)', delegatable: true }))).toBe('admitted'); |
| 186 | + }); |
| 187 | + |
| 188 | + it('control: forging provenance in a row-state patch is still refused (a)', async () => { |
| 189 | + const h = await boot(); |
| 190 | + const refused = await h.write(byId('pos_admin', { active: false, managed_by: 'package' })); |
| 191 | + expect(refused).toMatchObject(REFUSED); |
| 192 | + expect((refused as any).message).toContain('cannot stamp'); |
| 193 | + }); |
| 194 | +}); |
| 195 | + |
| 196 | +describe('[#22360] a filtered update over package position rows', () => { |
| 197 | + const PKG_NAMES = { name: { $in: ['field_rep', 'auditor'] } }; |
| 198 | + |
| 199 | + it('a row-state-only patch over package rows passes', async () => { |
| 200 | + const h = await boot(); |
| 201 | + expect(await h.write(update('sys_position', { active: false }, PKG_NAMES))).toBe('admitted'); |
| 202 | + expect(await h.write(update('sys_position', { is_default: false }, PKG_NAMES))).toBe('admitted'); |
| 203 | + }); |
| 204 | + |
| 205 | + it('a label patch over a package row is refused', async () => { |
| 206 | + const h = await boot(); |
| 207 | + const refused = await h.write(update('sys_position', { label: 'Renamed' }, PKG_NAMES)); |
| 208 | + expect(refused).toMatchObject(REFUSED); |
| 209 | + expect((refused as any).message).toContain('provided by the platform or an application package'); |
| 210 | + }); |
| 211 | + |
| 212 | + it('a row-state-only patch whose filter also reaches a built-in is refused', async () => { |
| 213 | + const h = await boot(); |
| 214 | + expect(await h.write(update('sys_position', { active: false }, { name: { $in: ['field_rep', 'everyone'] } }))) |
| 215 | + .toMatchObject(REFUSED); |
| 216 | + // A whole-table write matches every built-in. |
| 217 | + expect(await h.write({ object: 'sys_position', operation: 'update', data: { active: false }, options: {} })) |
| 218 | + .toMatchObject(REFUSED); |
| 219 | + }); |
| 220 | + |
| 221 | + it('control: a filtered delete over package rows stays refused', async () => { |
| 222 | + const h = await boot(); |
| 223 | + expect(await h.write({ object: 'sys_position', operation: 'delete', options: { where: PKG_NAMES } })) |
| 224 | + .toMatchObject(REFUSED); |
| 225 | + }); |
| 226 | +}); |
0 commit comments