|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#2909 P0/T1] sys_sharing_rule provenance + seed-not-clobber. |
| 5 | + * |
| 6 | + * sys_sharing_rule is record-authoritative (ADR-0094 addendum): declared |
| 7 | + * rules are a boot seed, the row is the authority. The seed (defineRule with |
| 8 | + * managedBy package/platform): |
| 9 | + * - adopts pristine/legacy rows and keeps updating them (package upgrades |
| 10 | + * stay deliverable), |
| 11 | + * - NEVER overwrites a row the admin authored (managed_by admin) or |
| 12 | + * customized — most importantly an admin's `active: false` on an |
| 13 | + * over-sharing rule must survive redeploys (no resurrection), |
| 14 | + * - non-seed defineRule keeps its historical clobber semantics. |
| 15 | + * The `customized` stamp is applied by a beforeUpdate hook on any |
| 16 | + * non-system edit of a package/platform row. |
| 17 | + */ |
| 18 | + |
| 19 | +import { describe, it, expect, beforeEach, vi } from 'vitest'; |
| 20 | +import { SharingService } from './sharing-service.js'; |
| 21 | +import { SharingRuleService } from './sharing-rule-service.js'; |
| 22 | +import { bindRuleProvenanceStamp, SHARING_RULE_PROVENANCE_PACKAGE } from './sharing-rule-provenance.js'; |
| 23 | + |
| 24 | +interface Row { [k: string]: any } |
| 25 | + |
| 26 | +const SYS = { isSystem: true } as any; |
| 27 | + |
| 28 | +function makeEngine() { |
| 29 | + const tables: Record<string, Row[]> = {}; |
| 30 | + const hooks: Array<{ event: string; handler: (ctx: any) => any; options: Row }> = []; |
| 31 | + const ensure = (n: string) => (tables[n] ??= []); |
| 32 | + function matches(row: Row, f: any): boolean { |
| 33 | + if (!f || typeof f !== 'object') return true; |
| 34 | + for (const [k, v] of Object.entries(f)) { |
| 35 | + if (row[k] !== v) return false; |
| 36 | + } |
| 37 | + return true; |
| 38 | + } |
| 39 | + return { |
| 40 | + _tables: tables, |
| 41 | + _hooks: hooks, |
| 42 | + getSchema() { return undefined; }, |
| 43 | + async find(o: string, opts?: any) { |
| 44 | + const f = opts?.filter ?? opts?.where; |
| 45 | + return ensure(o).filter((r) => matches(r, f)).slice(0, opts?.limit ?? 10000); |
| 46 | + }, |
| 47 | + async insert(o: string, data: any) { const row = { ...data }; ensure(o).push(row); return row; }, |
| 48 | + async update(o: string, idOrData: any, dataOrOpts?: any) { |
| 49 | + const data = typeof idOrData === 'object' ? idOrData : dataOrOpts; |
| 50 | + const id = typeof idOrData === 'object' ? idOrData.id : idOrData; |
| 51 | + const t = ensure(o); const i = t.findIndex((r) => r.id === id); |
| 52 | + if (i >= 0) t[i] = { ...t[i], ...data }; |
| 53 | + return t[i]; |
| 54 | + }, |
| 55 | + async delete(o: string, opts?: any) { |
| 56 | + const t = ensure(o); const where = opts?.where ?? {}; |
| 57 | + for (let i = t.length - 1; i >= 0; i--) if (matches(t[i], where)) t.splice(i, 1); |
| 58 | + return { ok: true }; |
| 59 | + }, |
| 60 | + registerHook(event: string, handler: (ctx: any) => any, options: Row = {}) { |
| 61 | + hooks.push({ event, handler, options }); |
| 62 | + }, |
| 63 | + unregisterHooksByPackage(packageId: string) { |
| 64 | + let removed = 0; |
| 65 | + for (let i = hooks.length - 1; i >= 0; i--) { |
| 66 | + if (hooks[i].options.packageId === packageId) { hooks.splice(i, 1); removed++; } |
| 67 | + } |
| 68 | + return removed; |
| 69 | + }, |
| 70 | + /** Test helper: simulate an engine update passing through beforeUpdate hooks. */ |
| 71 | + async updateThroughHooks(o: string, id: string, data: Row, session: Row) { |
| 72 | + for (const h of hooks) { |
| 73 | + if (h.event === 'beforeUpdate' && h.options.object === o) { |
| 74 | + await h.handler({ session, input: { id, data } }); |
| 75 | + } |
| 76 | + } |
| 77 | + return this.update(o, id, data); |
| 78 | + }, |
| 79 | + }; |
| 80 | +} |
| 81 | + |
| 82 | +const DECLARED = { |
| 83 | + name: 'red_projects_to_exec', label: 'Red projects → exec', object: 'showcase_project', |
| 84 | + criteria: { health: 'red' }, |
| 85 | + recipientType: 'position' as const, recipientId: 'exec', accessLevel: 'read' as const, |
| 86 | + managedBy: 'package' as const, |
| 87 | +}; |
| 88 | + |
| 89 | +describe('defineRule seed-not-clobber (#2909 P0/T1)', () => { |
| 90 | + let engine: ReturnType<typeof makeEngine>; |
| 91 | + let rules: SharingRuleService; |
| 92 | + |
| 93 | + beforeEach(() => { |
| 94 | + engine = makeEngine(); |
| 95 | + const sharing = new SharingService({ engine: engine as any }); |
| 96 | + rules = new SharingRuleService({ engine: engine as any, sharing }); |
| 97 | + }); |
| 98 | + |
| 99 | + it('seeds a new declared rule with managed_by:package and customized:false', async () => { |
| 100 | + const r = await rules.defineRule(DECLARED as any, SYS); |
| 101 | + expect(r.managed_by).toBe('package'); |
| 102 | + expect(r.customized).toBe(false); |
| 103 | + expect(engine._tables.sys_sharing_rule[0]).toMatchObject({ managed_by: 'package', customized: false }); |
| 104 | + }); |
| 105 | + |
| 106 | + it('keeps updating a PRISTINE seeded rule on re-seed (package upgrades deliverable)', async () => { |
| 107 | + await rules.defineRule(DECLARED as any, SYS); |
| 108 | + const r = await rules.defineRule({ ...DECLARED, label: 'Red projects → exec v2', accessLevel: 'edit' } as any, SYS); |
| 109 | + expect(r.label).toBe('Red projects → exec v2'); |
| 110 | + expect(r.access_level).toBe('edit'); |
| 111 | + expect(engine._tables.sys_sharing_rule).toHaveLength(1); |
| 112 | + }); |
| 113 | + |
| 114 | + it('ADOPTS a legacy row with no provenance (stamps managed_by on re-seed)', async () => { |
| 115 | + engine._tables.sys_sharing_rule = [{ |
| 116 | + id: 'srule_legacy', name: DECLARED.name, label: 'old', object_name: 'showcase_project', |
| 117 | + criteria_json: null, recipient_type: 'position', recipient_id: 'exec', |
| 118 | + access_level: 'read', active: true, |
| 119 | + }]; |
| 120 | + const r = await rules.defineRule(DECLARED as any, SYS); |
| 121 | + expect(r.managed_by).toBe('package'); |
| 122 | + expect(engine._tables.sys_sharing_rule[0].managed_by).toBe('package'); |
| 123 | + }); |
| 124 | + |
| 125 | + it('does NOT resurrect an admin-deactivated seeded rule (customized survives redeploys)', async () => { |
| 126 | + await rules.defineRule(DECLARED as any, SYS); |
| 127 | + // Admin deactivates the over-sharing rule (stamp applied by the hook — here direct). |
| 128 | + const row = engine._tables.sys_sharing_rule[0]; |
| 129 | + await engine.update('sys_sharing_rule', { id: row.id, active: false, customized: true }); |
| 130 | + // Next boot re-seeds with active:true… |
| 131 | + const r = await rules.defineRule(DECLARED as any, SYS); |
| 132 | + expect(r.active).toBe(false); |
| 133 | + expect(engine._tables.sys_sharing_rule[0].active).toBe(false); |
| 134 | + }); |
| 135 | + |
| 136 | + it('never touches an admin-authored rule that collides on name (admin row wins + warn)', async () => { |
| 137 | + const warn = vi.fn(); |
| 138 | + const sharing = new SharingService({ engine: engine as any }); |
| 139 | + const svc = new SharingRuleService({ engine: engine as any, sharing, logger: { warn } }); |
| 140 | + await svc.defineRule({ ...DECLARED, managedBy: undefined, label: 'Admin authored' } as any, SYS); |
| 141 | + expect(engine._tables.sys_sharing_rule[0].managed_by).toBe('admin'); |
| 142 | + const r = await svc.defineRule(DECLARED as any, SYS); |
| 143 | + expect(r.label).toBe('Admin authored'); |
| 144 | + expect(engine._tables.sys_sharing_rule[0].label).toBe('Admin authored'); |
| 145 | + expect(warn).toHaveBeenCalled(); |
| 146 | + }); |
| 147 | + |
| 148 | + it('non-seed defineRule keeps clobber semantics and stamps admin provenance on insert', async () => { |
| 149 | + const first = await rules.defineRule({ ...DECLARED, managedBy: undefined } as any, SYS); |
| 150 | + expect(first.managed_by).toBe('admin'); |
| 151 | + const r = await rules.defineRule({ ...DECLARED, managedBy: undefined, label: 'edited' } as any, SYS); |
| 152 | + expect(r.label).toBe('edited'); |
| 153 | + // Programmatic re-define does not touch provenance columns. |
| 154 | + expect(engine._tables.sys_sharing_rule[0].managed_by).toBe('admin'); |
| 155 | + }); |
| 156 | +}); |
| 157 | + |
| 158 | +describe('provenance stamp hook (#2909 T1)', () => { |
| 159 | + let engine: ReturnType<typeof makeEngine>; |
| 160 | + let rules: SharingRuleService; |
| 161 | + |
| 162 | + beforeEach(async () => { |
| 163 | + engine = makeEngine(); |
| 164 | + const sharing = new SharingService({ engine: engine as any }); |
| 165 | + rules = new SharingRuleService({ engine: engine as any, sharing }); |
| 166 | + await rules.defineRule(DECLARED as any, SYS); |
| 167 | + bindRuleProvenanceStamp(engine as any); |
| 168 | + }); |
| 169 | + |
| 170 | + it('stamps customized:true when a non-system caller edits a package rule', async () => { |
| 171 | + const row = engine._tables.sys_sharing_rule[0]; |
| 172 | + await engine.updateThroughHooks('sys_sharing_rule', row.id, { active: false }, { userId: 'admin1' }); |
| 173 | + expect(engine._tables.sys_sharing_rule[0]).toMatchObject({ active: false, customized: true }); |
| 174 | + }); |
| 175 | + |
| 176 | + it('does NOT stamp on isSystem writes (seeder/backfill are not customizations)', async () => { |
| 177 | + const row = engine._tables.sys_sharing_rule[0]; |
| 178 | + await engine.updateThroughHooks('sys_sharing_rule', row.id, { label: 'reseed' }, { isSystem: true }); |
| 179 | + expect(engine._tables.sys_sharing_rule[0].customized).toBe(false); |
| 180 | + }); |
| 181 | + |
| 182 | + it('does NOT stamp admin-authored rows (an env row IS the definition)', async () => { |
| 183 | + await rules.defineRule({ ...DECLARED, name: 'admin_rule', managedBy: undefined } as any, SYS); |
| 184 | + const adminRow = engine._tables.sys_sharing_rule.find((r) => r.name === 'admin_rule')!; |
| 185 | + await engine.updateThroughHooks('sys_sharing_rule', adminRow.id, { active: false }, { userId: 'admin1' }); |
| 186 | + expect(engine._tables.sys_sharing_rule.find((r) => r.name === 'admin_rule')!.customized).toBe(false); |
| 187 | + }); |
| 188 | + |
| 189 | + it('ignores multi-row updates (no id) without crashing', async () => { |
| 190 | + const hook = engine._hooks.find((h) => h.options.packageId === SHARING_RULE_PROVENANCE_PACKAGE)!; |
| 191 | + await expect(hook.handler({ session: { userId: 'admin1' }, input: { data: { active: false } } })).resolves.toBeUndefined(); |
| 192 | + }); |
| 193 | + |
| 194 | + it('end-to-end: admin edit through hooks → next seed does not clobber', async () => { |
| 195 | + const row = engine._tables.sys_sharing_rule[0]; |
| 196 | + await engine.updateThroughHooks('sys_sharing_rule', row.id, { active: false }, { userId: 'admin1' }); |
| 197 | + const r = await rules.defineRule(DECLARED as any, SYS); |
| 198 | + expect(r.active).toBe(false); |
| 199 | + }); |
| 200 | +}); |
0 commit comments