|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [ADR-0131 D4] The grant that names nothing, as each `plugin-auth` grant |
| 5 | + * reader treats it once the readers key on `sys_user_permission_set.permission_set`. |
| 6 | + * |
| 7 | + * A grant written before the name column existed carries `NULL` until the |
| 8 | + * one-time backfill (`plugin-security`, `kernel:bootstrapped`) names it; on an |
| 9 | + * upgraded deployment's first boot every grant is unnamed when the |
| 10 | + * `kernel:ready` passes run, and the backfill leaves some unnamed for good (an |
| 11 | + * id with no set row, or a set row of another organization). Each reader takes |
| 12 | + * its fail-closed direction: |
| 13 | + * |
| 14 | + * - **the last-administrator guard** counts no administrator through it, and |
| 15 | + * reads it as evidence that the environment is NOT fresh — so the bootstrap |
| 16 | + * window never opens on an environment whose administrator holds one; |
| 17 | + * - **the default-organization bootstrap** does not read it as the platform |
| 18 | + * administrator: it confers an owner membership, and an unnamed grant |
| 19 | + * confers nothing. |
| 20 | + * |
| 21 | + * And the guard's simulation of a write that re-points a grant's id without |
| 22 | + * its name: the platform derives that name after the guard runs, so the guard |
| 23 | + * reads it as taking the standing away — while an id echoed unchanged keeps it. |
| 24 | + * |
| 25 | + * Real ObjectQL over the SQL driver with the real `SecurityPlugin` (its objects |
| 26 | + * and its name hooks); a grant is unnamed by writing `NULL` with the name hooks |
| 27 | + * unbound, the state the backfill leaves. |
| 28 | + */ |
| 29 | + |
| 30 | +import { describe, it, expect, afterEach, vi } from 'vitest'; |
| 31 | +import { ObjectQL } from '@objectstack/objectql'; |
| 32 | +import { SqlDriver } from '@objectstack/driver-sql'; |
| 33 | +import { resetPlatformAdminEmailMemo } from '@objectstack/core'; |
| 34 | +import { SecurityPlugin, bootstrapPlatformAdmin } from '@objectstack/plugin-security'; |
| 35 | +import { SysUser, SysAccount, SysMember, SysOrganization } from '@objectstack/platform-objects/identity'; |
| 36 | + |
| 37 | +import { registerLastAdminGuard, type LastAdminGuardEngine } from './last-admin-guard.js'; |
| 38 | +import { ensureDefaultOrganization } from './ensure-default-organization.js'; |
| 39 | + |
| 40 | +const SYS = { context: { isSystem: true } } as any; |
| 41 | +const NAME_HOOKS = 'plugin-security:grant-permission-set-name'; |
| 42 | + |
| 43 | +const engines: ObjectQL[] = []; |
| 44 | +afterEach(async () => { |
| 45 | + vi.restoreAllMocks(); |
| 46 | + resetPlatformAdminEmailMemo(); |
| 47 | + while (engines.length) { |
| 48 | + try { await engines.pop()?.destroy(); } catch { /* noop */ } |
| 49 | + } |
| 50 | +}); |
| 51 | + |
| 52 | +interface Rig { |
| 53 | + engine: ObjectQL; |
| 54 | + /** Re-bind the plugin's name hooks after `unname` (a fresh start of the plugin's hook half). */ |
| 55 | + plugin: SecurityPlugin; |
| 56 | +} |
| 57 | + |
| 58 | +/** `single` posture; the first user is promoted to platform administrator — the sole administrator. */ |
| 59 | +async function soleGrantAnchoredAdmin(): Promise<Rig> { |
| 60 | + resetPlatformAdminEmailMemo(); |
| 61 | + const engine = new ObjectQL(); |
| 62 | + engine.registerDriver( |
| 63 | + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), |
| 64 | + true, |
| 65 | + ); |
| 66 | + await engine.init(); |
| 67 | + engines.push(engine); |
| 68 | + let manifest: { objects?: unknown[]; permissions?: unknown[] } = {}; |
| 69 | + const services: Record<string, unknown> = { |
| 70 | + manifest: { register: (m: any) => { manifest = m; } }, |
| 71 | + objectql: engine, |
| 72 | + metadata: { |
| 73 | + get: async (_type: string, name: string) => engine.getSchema(name) ?? null, |
| 74 | + list: async () => [...((manifest.permissions as unknown[]) ?? [])], |
| 75 | + }, |
| 76 | + }; |
| 77 | + const ctx: any = { |
| 78 | + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, |
| 79 | + hook: vi.fn(), |
| 80 | + registerService: vi.fn(), |
| 81 | + getService: (name: string) => { |
| 82 | + if (!(name in services)) throw new Error(`service not registered: ${name}`); |
| 83 | + return services[name]; |
| 84 | + }, |
| 85 | + }; |
| 86 | + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' }); |
| 87 | + await plugin.init(ctx); |
| 88 | + engine.registerApp({ |
| 89 | + id: 'com.objectstack.qa.grant-readers-unnamed-auth', |
| 90 | + name: 'Grant readers — unnamed grant (auth)', |
| 91 | + version: '1.0.0', |
| 92 | + type: 'plugin', |
| 93 | + scope: 'system', |
| 94 | + objects: [ |
| 95 | + SysUser, SysAccount, SysMember, SysOrganization, |
| 96 | + ...(manifest.objects ?? []).filter((o: any) => |
| 97 | + ['sys_position', 'sys_user_position', 'sys_permission_set', 'sys_position_permission_set', 'sys_user_permission_set'] |
| 98 | + .includes(o?.name)), |
| 99 | + ], |
| 100 | + } as any); |
| 101 | + await engine.syncSchemas(); |
| 102 | + await plugin.start(ctx); |
| 103 | + vi.spyOn((engine as any).logger, 'warn').mockImplementation(() => undefined); |
| 104 | + registerLastAdminGuard(engine as unknown as LastAdminGuardEngine, { |
| 105 | + packageId: 'test.grant-readers-unnamed', |
| 106 | + logger: { info: () => undefined, warn: () => undefined }, |
| 107 | + }); |
| 108 | + for (const [id, createdAt] of [['usr_admin', '2025-01-01T00:00:00.000Z'], ['usr_member', '2025-03-01T00:00:00.000Z']]) { |
| 109 | + await engine.insert( |
| 110 | + 'sys_user', { id, email: `${id}@un.example`, name: id, created_at: createdAt, email_verified: true, banned: false }, SYS, |
| 111 | + ); |
| 112 | + await engine.insert( |
| 113 | + 'sys_account', { id: `acc_${id}`, user_id: id, account_id: `${id}@un.example`, provider_id: 'credential' }, SYS, |
| 114 | + ); |
| 115 | + } |
| 116 | + const boot = await bootstrapPlatformAdmin(engine, (manifest.permissions ?? []) as any[]); |
| 117 | + expect(boot).toMatchObject({ adminPromoted: true }); |
| 118 | + return { engine, plugin }; |
| 119 | +} |
| 120 | + |
| 121 | +const adminGrant = async (engine: ObjectQL): Promise<any> => |
| 122 | + ((await engine.find('sys_user_permission_set', { where: { user_id: 'usr_admin' }, ...SYS })) as any[])[0]; |
| 123 | + |
| 124 | +async function unnameAdminGrant(engine: ObjectQL): Promise<void> { |
| 125 | + (engine as any).unregisterHooksByPackage(NAME_HOOKS); |
| 126 | + await engine.update('sys_user_permission_set', { permission_set: null }, { where: { user_id: 'usr_admin' }, multi: true, ...SYS }); |
| 127 | + expect((await adminGrant(engine)).permission_set ?? null).toBeNull(); |
| 128 | +} |
| 129 | + |
| 130 | +const ban = (engine: ObjectQL, id: string) => engine.update('sys_user', { id, banned: true }, SYS); |
| 131 | + |
| 132 | +describe('[ADR-0131 D4] a grant that names nothing — the last-administrator guard', () => { |
| 133 | + it('control — named, the grant is the last administrator: banning its holder is refused', async () => { |
| 134 | + const { engine } = await soleGrantAnchoredAdmin(); |
| 135 | + expect((await adminGrant(engine)).permission_set).toBe('admin_full_access'); |
| 136 | + await expect(ban(engine, 'usr_admin')).rejects.toThrow(/last administrator/i); |
| 137 | + }); |
| 138 | + |
| 139 | + it('unnamed, it counts no administrator but is evidence: the bootstrap window does not open', async () => { |
| 140 | + const { engine } = await soleGrantAnchoredAdmin(); |
| 141 | + await unnameAdminGrant(engine); |
| 142 | + await expect(ban(engine, 'usr_admin')).rejects.toThrow(/not the bootstrap window/i); |
| 143 | + await expect(ban(engine, 'usr_admin')).rejects.toThrow(/no permission-set name yet/); |
| 144 | + await expect(ban(engine, 'usr_member')).rejects.toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); |
| 145 | + }); |
| 146 | + |
| 147 | + it('re-pointing the sole administrator’s grant by id is read as taking the standing away', async () => { |
| 148 | + const { engine } = await soleGrantAnchoredAdmin(); |
| 149 | + const grant = await adminGrant(engine); |
| 150 | + const [viewer] = (await engine.find('sys_permission_set', { where: { name: 'viewer_readonly' }, ...SYS })) as any[]; |
| 151 | + await expect(engine.update('sys_user_permission_set', { id: grant.id, permission_set_id: viewer.id }, SYS)) |
| 152 | + .rejects.toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); |
| 153 | + expect((await adminGrant(engine)).permission_set).toBe('admin_full_access'); |
| 154 | + }); |
| 155 | + |
| 156 | + it('echoing the grant’s own id keeps the standing: the write is permitted', async () => { |
| 157 | + const { engine } = await soleGrantAnchoredAdmin(); |
| 158 | + const grant = await adminGrant(engine); |
| 159 | + await engine.update( |
| 160 | + 'sys_user_permission_set', |
| 161 | + { id: grant.id, permission_set_id: grant.permission_set_id, reason: 'renewed' }, |
| 162 | + SYS, |
| 163 | + ); |
| 164 | + expect((await adminGrant(engine)).reason).toBe('renewed'); |
| 165 | + }); |
| 166 | +}); |
| 167 | + |
| 168 | +describe('[ADR-0131 D4] a grant that names nothing — the default-organization bootstrap', () => { |
| 169 | + it('control — named, the grant holder is bound as the Default Organization owner', async () => { |
| 170 | + const { engine } = await soleGrantAnchoredAdmin(); |
| 171 | + const res = await ensureDefaultOrganization(engine as any, { logger: { info: () => undefined, warn: () => undefined } }); |
| 172 | + expect(res.memberCreated).toBe(true); |
| 173 | + }); |
| 174 | + |
| 175 | + it('unnamed, nobody is read as the platform administrator: `no_admin`, nothing is bound', async () => { |
| 176 | + const { engine } = await soleGrantAnchoredAdmin(); |
| 177 | + await unnameAdminGrant(engine); |
| 178 | + const res = await ensureDefaultOrganization(engine as any, { logger: { info: () => undefined, warn: () => undefined } }); |
| 179 | + expect(res).toMatchObject({ memberCreated: false, reason: 'no_admin' }); |
| 180 | + expect(await engine.find('sys_member', { where: { user_id: 'usr_admin' }, ...SYS })).toEqual([]); |
| 181 | + }); |
| 182 | +}); |
0 commit comments