|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * A seeded boot reads the `auth` settings AFTER the settings engine binds |
| 5 | + * (#22257). |
| 6 | + * |
| 7 | + * ## The defect |
| 8 | + * |
| 9 | + * `SettingsServicePlugin` binds its data engine from a `kernel:ready` hook it |
| 10 | + * registers in `start()`. `AuthPlugin` declares |
| 11 | + * `optionalDependencies: ['com.objectstack.service.settings']`, so its own |
| 12 | + * `kernel:ready` hooks are registered later and fire after the bind |
| 13 | + * (`auth-settings-ordering.pin.test.ts`). That edge orders HOOKS and nothing |
| 14 | + * else. `AppPlugin.start()` emits `app:seeded` when its inline seed lands, and |
| 15 | + * on `os serve` / `os dev` the app plugin starts after the auth plugin, so the |
| 16 | + * event arrives during Phase 2 — and the ADR-0093 D6 backfill's `app:seeded` |
| 17 | + * handler went `runBackfill` → `ensureAuthSettingsBound` → `bindAuthSettings` → |
| 18 | + * `getNamespace('auth')` while the engine was still unbound. Measured on the |
| 19 | + * showcase (`os dev --seed-admin --fresh`): one `[SettingsService] Pre-bind READ |
| 20 | + * of namespace 'auth'` on every boot, logged between the seed's completion and |
| 21 | + * the `kernel:ready` trigger, and the auth binding computed from the manifest |
| 22 | + * defaults. `check:settings-bind-window` walks `kernel:ready` handlers only, so |
| 23 | + * an `app:seeded` handler was outside its population. |
| 24 | + * |
| 25 | + * ## The composition |
| 26 | + * |
| 27 | + * The cheapest real one that reproduces it: a real `ObjectKernel`, a real |
| 28 | + * ObjectQL engine on in-memory SQLite, the REAL `SettingsServicePlugin` (its |
| 29 | + * bind hook and its reporter are the subject), the real `AuthPlugin` used |
| 30 | + * BEFORE the settings plugin (the `os serve` order), and an app plugin in |
| 31 | + * `AppPlugin`'s place: it starts after the auth plugin, writes the row a |
| 32 | + * previous boot persisted, and emits `app:seeded` from its own `start()`. |
| 33 | + * |
| 34 | + * It awaits the event, which `AppPlugin` does not. That is the stricter form: |
| 35 | + * the handler's whole chain then runs inside Phase 2, so a read it makes cannot |
| 36 | + * slip past the bind by timing. |
| 37 | + * |
| 38 | + * ## What is asserted |
| 39 | + * |
| 40 | + * 1. the window is real in this composition — at the moment `app:seeded` |
| 41 | + * fires, the settings engine is NOT bound. Without it the next assertion |
| 42 | + * could pass vacuously; |
| 43 | + * 2. no `Pre-bind READ` is reported (the card's Done-when); |
| 44 | + * 3. the first `getNamespace('auth')` the auth plugin issues answers the |
| 45 | + * PERSISTED value, and the one-time pass decides under it — the value is |
| 46 | + * observable, so the pin names it rather than inferring it from silence. |
| 47 | + * |
| 48 | + * The control case forces a pre-bind read of `auth` in the same composition |
| 49 | + * and expects exactly one report: proof that the logger spy here sees the |
| 50 | + * reporter at all. The reporter's own suite |
| 51 | + * (`settings-prebind-read-warning.test.ts`) keeps pinning its text. |
| 52 | + * |
| 53 | + * ## Resolution |
| 54 | + * |
| 55 | + * `AuthPlugin` is imported from SOURCE (relative). `@objectstack/service-settings` |
| 56 | + * is aliased to its `src/` in this package's `vitest.config.ts`, so the |
| 57 | + * reporter and the bind hook are the checkout's too. `ObjectKernel`, |
| 58 | + * `ObjectQLPlugin` and `SqlDriver` are the fixed instruments, read from `dist/` |
| 59 | + * as this package's other kernel tests read them. |
| 60 | + */ |
| 61 | + |
| 62 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; |
| 63 | +import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; |
| 64 | +import { ObjectQLPlugin } from '@objectstack/objectql'; |
| 65 | +import { SqlDriver } from '@objectstack/driver-sql'; |
| 66 | +import { |
| 67 | + InMemoryCryptoProvider, |
| 68 | + SettingsService, |
| 69 | + SettingsServicePlugin, |
| 70 | +} from '@objectstack/service-settings'; |
| 71 | +import { AuthPlugin } from './auth-plugin.js'; |
| 72 | + |
| 73 | +vi.mock('./membership-backfill-ledger.js', async (importOriginal) => { |
| 74 | + const actual = await importOriginal<typeof import('./membership-backfill-ledger.js')>(); |
| 75 | + return { |
| 76 | + ...actual, |
| 77 | + runOneTimeMembershipBackfill: vi.fn(actual.runOneTimeMembershipBackfill), |
| 78 | + }; |
| 79 | +}); |
| 80 | + |
| 81 | +import { runOneTimeMembershipBackfill } from './membership-backfill-ledger.js'; |
| 82 | + |
| 83 | +const backfillSpy = vi.mocked(runOneTimeMembershipBackfill); |
| 84 | + |
| 85 | +const SYS = { isSystem: true } as const; |
| 86 | + |
| 87 | +/** |
| 88 | + * The persisted value. The manifest default for `auth.membership_policy` is |
| 89 | + * `auto`, so a read answered from the in-memory fallback cannot produce this. |
| 90 | + */ |
| 91 | +const PERSISTED_POLICY = 'invite-only'; |
| 92 | + |
| 93 | +/** Env the auth settings read or the backfill branches on; cleared per case. */ |
| 94 | +const ENV_KEYS = [ |
| 95 | + 'OS_AUTH_MEMBERSHIP_POLICY', |
| 96 | + 'OS_SKIP_MEMBERSHIP_BACKFILL', |
| 97 | + 'OS_TENANCY_POSTURE', |
| 98 | + 'OS_MULTI_ORG_ENABLED', |
| 99 | +] as const; |
| 100 | + |
| 101 | +/** Publishes an in-memory SQLite driver the way a datasource plugin does. */ |
| 102 | +function sqliteDriverPlugin(): Plugin { |
| 103 | + return { |
| 104 | + name: 'test.driver.sqlite', |
| 105 | + type: 'standard', |
| 106 | + version: '1.0.0', |
| 107 | + async init(ctx: PluginContext) { |
| 108 | + ctx.registerService( |
| 109 | + 'driver.default', |
| 110 | + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), |
| 111 | + ); |
| 112 | + }, |
| 113 | + }; |
| 114 | +} |
| 115 | + |
| 116 | +/** What the app plugin saw at the moment it emitted `app:seeded`. */ |
| 117 | +interface SeedObservation { |
| 118 | + /** Whether `SettingsService` had its data engine bound at that instant. */ |
| 119 | + engineBound?: boolean; |
| 120 | +} |
| 121 | + |
| 122 | +/** |
| 123 | + * An app plugin in `AppPlugin`'s place: it starts after the auth plugin (no |
| 124 | + * edge between them, registered later), and its `start()` writes rows and then |
| 125 | + * emits `app:seeded`, as `AppPlugin.start()` does when its inline seed lands. |
| 126 | + * |
| 127 | + * The row is the `auth.membership_policy` a previous boot persisted — the |
| 128 | + * `global` rung, so `sys_platform_setting` (ADR-0131 D7). |
| 129 | + * |
| 130 | + * `forcePreBindRead` is the control: the same plugin reads the `auth` |
| 131 | + * namespace itself, inside the window. |
| 132 | + */ |
| 133 | +function seedingAppPlugin(seen: SeedObservation, opts: { forcePreBindRead?: boolean } = {}): Plugin { |
| 134 | + return { |
| 135 | + name: 'com.example.seeded-app', |
| 136 | + type: 'app', |
| 137 | + version: '1.0.0', |
| 138 | + dependencies: ['com.objectstack.engine.objectql'], |
| 139 | + async init() {}, |
| 140 | + async start(ctx: PluginContext) { |
| 141 | + const ql = ctx.getService<{ insert(o: string, d: unknown, opts?: unknown): Promise<unknown> }>('objectql'); |
| 142 | + await ql.insert( |
| 143 | + 'sys_platform_setting', |
| 144 | + { namespace: 'auth', key: 'membership_policy', value: PERSISTED_POLICY, encrypted: false, locked: false }, |
| 145 | + { context: SYS }, |
| 146 | + ); |
| 147 | + const settings = ctx.getService<SettingsService>('settings'); |
| 148 | + // Reaching into the private field on purpose, as the reporter's own suite |
| 149 | + // does: "was the engine bound at this instant" is the fact the window is |
| 150 | + // defined by, and there is no public spelling of it. |
| 151 | + seen.engineBound = Boolean((settings as unknown as { engine?: unknown }).engine); |
| 152 | + if (opts.forcePreBindRead) await settings.getNamespace('auth'); |
| 153 | + await ctx.trigger('app:seeded', { appId: 'com.example.seeded-app', overBudget: false }); |
| 154 | + }, |
| 155 | + }; |
| 156 | +} |
| 157 | + |
| 158 | +describe('a seeded boot reads the auth settings after the settings engine binds (#22257)', () => { |
| 159 | + let kernel: ObjectKernel | undefined; |
| 160 | + const savedEnv: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>> = {}; |
| 161 | + |
| 162 | + beforeEach(() => { |
| 163 | + for (const key of ENV_KEYS) { |
| 164 | + savedEnv[key] = process.env[key]; |
| 165 | + delete process.env[key]; |
| 166 | + } |
| 167 | + backfillSpy.mockClear(); |
| 168 | + }); |
| 169 | + |
| 170 | + afterEach(async () => { |
| 171 | + try { |
| 172 | + await kernel?.shutdown(); |
| 173 | + } catch { |
| 174 | + /* a refused boot leaves the kernel stopped */ |
| 175 | + } |
| 176 | + kernel = undefined; |
| 177 | + for (const key of ENV_KEYS) { |
| 178 | + if (savedEnv[key] === undefined) delete process.env[key]; |
| 179 | + else process.env[key] = savedEnv[key]; |
| 180 | + } |
| 181 | + vi.restoreAllMocks(); |
| 182 | + }); |
| 183 | + |
| 184 | + /** |
| 185 | + * Boot the composition. The kernel logger's `warn` is spied on the INSTANCE: |
| 186 | + * `SettingsServicePlugin.init` stores `ctx.logger`, which is that same object, |
| 187 | + * so this is what the reporter really calls. |
| 188 | + */ |
| 189 | + async function boot(opts: { forcePreBindRead?: boolean } = {}) { |
| 190 | + const namespaceReads = vi.spyOn(SettingsService.prototype, 'getNamespace'); |
| 191 | + kernel = new ObjectKernel({ logger: { level: 'silent' } }); |
| 192 | + const kernelLogger = (kernel as unknown as { |
| 193 | + logger: { warn: (message: string, meta?: unknown) => void }; |
| 194 | + }).logger; |
| 195 | + const warn = vi.spyOn(kernelLogger, 'warn').mockImplementation(() => {}); |
| 196 | + |
| 197 | + const seen: SeedObservation = {}; |
| 198 | + await kernel.use(sqliteDriverPlugin()); |
| 199 | + await kernel.use(new ObjectQLPlugin()); |
| 200 | + // `os serve` uses the auth plugin before its capability loop registers the |
| 201 | + // settings plugin; the declared edge, not this order, puts settings first. |
| 202 | + await kernel.use(new AuthPlugin({ secret: 'test-secret-at-least-32-chars-long', baseUrl: 'http://localhost:3000' })); |
| 203 | + await kernel.use(new SettingsServicePlugin({ registerRoutes: false, cryptoProvider: new InMemoryCryptoProvider() })); |
| 204 | + await kernel.use(seedingAppPlugin(seen, opts)); |
| 205 | + await kernel.bootstrap(); |
| 206 | + |
| 207 | + const preBindReads = () => |
| 208 | + warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('Pre-bind READ')); |
| 209 | + return { seen, preBindReads, namespaceReads }; |
| 210 | + } |
| 211 | + |
| 212 | + it('reports no Pre-bind READ, and the auth binding and the one-time pass read the persisted value', async () => { |
| 213 | + const { seen, preBindReads, namespaceReads } = await boot(); |
| 214 | + |
| 215 | + // 1. The window is real here: `app:seeded` fired before the bind. |
| 216 | + expect(seen.engineBound, 'app:seeded must fire inside the pre-bind window, or this case measures nothing').toBe(false); |
| 217 | + |
| 218 | + // 2. The card's Done-when. |
| 219 | + expect(preBindReads()).toEqual([]); |
| 220 | + |
| 221 | + // 3. The value the auth binding saw is the persisted one, not the default. |
| 222 | + const authReadIndex = namespaceReads.mock.calls.findIndex(([namespace]) => namespace === 'auth'); |
| 223 | + expect(authReadIndex, 'the auth plugin never read the auth namespace').toBeGreaterThanOrEqual(0); |
| 224 | + const firstAuthRead = (await namespaceReads.mock.results[authReadIndex]!.value) as { |
| 225 | + values: Record<string, { value?: unknown; source?: unknown }>; |
| 226 | + }; |
| 227 | + expect(firstAuthRead.values.membership_policy).toMatchObject({ value: PERSISTED_POLICY, source: 'global' }); |
| 228 | + |
| 229 | + // …and the one-time membership pass decided under it, on every run. |
| 230 | + expect(backfillSpy).toHaveBeenCalled(); |
| 231 | + expect(backfillSpy.mock.calls.map(([, deps]) => deps.policy)).toEqual( |
| 232 | + backfillSpy.mock.calls.map(() => PERSISTED_POLICY), |
| 233 | + ); |
| 234 | + }, 30_000); |
| 235 | + |
| 236 | + it('control: a pre-bind read forced in the same composition IS reported, once, for auth', async () => { |
| 237 | + const { seen, preBindReads } = await boot({ forcePreBindRead: true }); |
| 238 | + |
| 239 | + expect(seen.engineBound).toBe(false); |
| 240 | + const reports = preBindReads(); |
| 241 | + expect(reports).toHaveLength(1); |
| 242 | + expect(reports[0]).toContain("Pre-bind READ of namespace 'auth'"); |
| 243 | + }, 30_000); |
| 244 | +}); |
0 commit comments