|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * The rule these pin (ADR-0069 D2): when a `cache` service is registered — as |
| 5 | + * a value or as a factory — the auth counters count in it; only when none is |
| 6 | + * registered do they fall back to the per-process store. |
| 7 | + * |
| 8 | + * Measured against REAL kernels, never a hand-built context: a mocked context |
| 9 | + * can carry any member it likes, including one the kernel never hands a |
| 10 | + * plugin, and a test against it passes while production counts elsewhere. |
| 11 | + * |
| 12 | + * - `resolveKernelCache` against an `ObjectKernel` context (factory, value, |
| 13 | + * none, not a store, the kernel's own `degraded` stand-in) and a |
| 14 | + * `LiteKernel` context (value). |
| 15 | + * - The composed stack — SQL driver, ObjectQL, `AuthPlugin`, a `cache` |
| 16 | + * registered by FACTORY — writes the rate-limit counter into that cache, |
| 17 | + * admits exactly `max` of a concurrent burst against one key while counting |
| 18 | + * there, and hands the OTP budget and the invitation preview the same store. |
| 19 | + * - The composed stack with NO cache plugin: the kernel injects its own |
| 20 | + * in-memory stand-in, and the counters keep the package's bounded |
| 21 | + * per-process store instead of counting in it. |
| 22 | + */ |
| 23 | + |
| 24 | +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; |
| 25 | +import { createMemoryCache, LiteKernel, ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; |
| 26 | +import { readServiceSelfInfo } from '@objectstack/spec/api'; |
| 27 | +import { ObjectQLPlugin } from '@objectstack/objectql'; |
| 28 | +import { SqlDriver } from '@objectstack/driver-sql'; |
| 29 | + |
| 30 | +import { AuthPlugin } from './auth-plugin.js'; |
| 31 | +import type { AuthManager } from './auth-manager.js'; |
| 32 | +import { resolveKernelCache } from './kernel-cache.js'; |
| 33 | +import { InProcessCounterStore, type CounterStore } from './rate-limit-storage.js'; |
| 34 | + |
| 35 | +/** A counter-capable cache: an `InProcessCounterStore` is exactly the slice the counters use. */ |
| 36 | +const makeCache = (): CounterStore => new InProcessCounterStore(); |
| 37 | + |
| 38 | +/** A plugin that registers `cache` the way the test asks, and keeps the context it was handed. */ |
| 39 | +function cachePlugin(mode: 'factory' | 'value' | 'none', cache: unknown): Plugin & { ctx?: PluginContext } { |
| 40 | + const plugin: Plugin & { ctx?: PluginContext } = { |
| 41 | + name: `test.cache.${mode}`, |
| 42 | + type: 'standard', |
| 43 | + version: '1.0.0', |
| 44 | + async init(ctx: PluginContext) { |
| 45 | + plugin.ctx = ctx; |
| 46 | + if (mode === 'factory') ctx.registerServiceFactory('cache', () => cache); |
| 47 | + if (mode === 'value') ctx.registerService('cache', cache); |
| 48 | + }, |
| 49 | + }; |
| 50 | + return plugin; |
| 51 | +} |
| 52 | + |
| 53 | +async function objectKernelContext(mode: 'factory' | 'value' | 'none', cache: unknown): Promise<PluginContext> { |
| 54 | + // No data plane here, so the system-requirement pass (which also injects the |
| 55 | + // kernel's own `cache` stand-in) is skipped: "none" really is none. |
| 56 | + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false, skipSystemValidation: true }); |
| 57 | + const plugin = cachePlugin(mode, cache); |
| 58 | + await kernel.use(plugin); |
| 59 | + await kernel.bootstrap(); |
| 60 | + return plugin.ctx!; |
| 61 | +} |
| 62 | + |
| 63 | +describe('resolveKernelCache — through the accessors a plugin context really carries', () => { |
| 64 | + it('ObjectKernel, `cache` registered by FACTORY: answers the factory-built cache', async () => { |
| 65 | + const cache = makeCache(); |
| 66 | + const ctx = await objectKernelContext('factory', cache); |
| 67 | + // The synchronous accessor cannot answer a factory that has not been built. |
| 68 | + expect(() => ctx.getService('cache')).toThrow('is async'); |
| 69 | + await expect(resolveKernelCache(ctx)).resolves.toBe(cache); |
| 70 | + }); |
| 71 | + |
| 72 | + it('ObjectKernel, `cache` registered as a VALUE: answers that value', async () => { |
| 73 | + const cache = makeCache(); |
| 74 | + const ctx = await objectKernelContext('value', cache); |
| 75 | + await expect(resolveKernelCache(ctx)).resolves.toBe(cache); |
| 76 | + }); |
| 77 | + |
| 78 | + it('ObjectKernel, no `cache` registered: answers undefined (the per-process fallback is right)', async () => { |
| 79 | + const ctx = await objectKernelContext('none', undefined); |
| 80 | + await expect(resolveKernelCache(ctx)).resolves.toBeUndefined(); |
| 81 | + }); |
| 82 | + |
| 83 | + it("the kernel's own in-memory stand-in (self-described `degraded`): answers undefined", async () => { |
| 84 | + const standIn = createMemoryCache(); |
| 85 | + expect(readServiceSelfInfo(standIn)?.status).toBe('degraded'); |
| 86 | + const ctx = await objectKernelContext('value', standIn); |
| 87 | + await expect(resolveKernelCache(ctx)).resolves.toBeUndefined(); |
| 88 | + }); |
| 89 | + |
| 90 | + it('a registered `cache` without get/set is not a counter store: answers undefined', async () => { |
| 91 | + const ctx = await objectKernelContext('value', { stats: () => ({}) }); |
| 92 | + await expect(resolveKernelCache(ctx)).resolves.toBeUndefined(); |
| 93 | + }); |
| 94 | + |
| 95 | + it('LiteKernel (no getServiceAsync, no factories), `cache` as a VALUE: answers that value', async () => { |
| 96 | + const cache = makeCache(); |
| 97 | + const kernel = new LiteKernel({ logger: { level: 'silent' } }); |
| 98 | + const plugin = cachePlugin('value', cache); |
| 99 | + kernel.use(plugin); |
| 100 | + await kernel.bootstrap(); |
| 101 | + await expect(resolveKernelCache(plugin.ctx!)).resolves.toBe(cache); |
| 102 | + }); |
| 103 | +}); |
| 104 | + |
| 105 | +function sqliteDriverPlugin(): Plugin { |
| 106 | + return { |
| 107 | + name: 'test.driver.sqlite', |
| 108 | + type: 'standard', |
| 109 | + version: '1.0.0', |
| 110 | + async init(ctx: PluginContext) { |
| 111 | + ctx.registerService( |
| 112 | + 'driver.default', |
| 113 | + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), |
| 114 | + ); |
| 115 | + }, |
| 116 | + }; |
| 117 | +} |
| 118 | + |
| 119 | +type ConsumeStorage = { consume: (key: string, rule: { window: number; max: number }) => Promise<{ allowed: boolean }> }; |
| 120 | +type CounterConfig = { rateLimitStorage: ConsumeStorage; sharedCounterStore: () => Promise<CounterStore> }; |
| 121 | + |
| 122 | +/** Boot SQL driver + ObjectQL (+ the given cache plugin) + AuthPlugin, with the kernel's system pass ON. */ |
| 123 | +async function bootStack(extra: Plugin[]): Promise<{ kernel: ObjectKernel; auth: AuthPlugin; config: CounterConfig }> { |
| 124 | + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); |
| 125 | + await kernel.use(sqliteDriverPlugin()); |
| 126 | + await kernel.use(new ObjectQLPlugin()); |
| 127 | + for (const p of extra) await kernel.use(p); |
| 128 | + const auth = new AuthPlugin({ secret: 'test-secret-at-least-32-chars-long-29053', baseUrl: 'http://localhost:3000' }); |
| 129 | + await kernel.use(auth); |
| 130 | + await kernel.bootstrap(); |
| 131 | + const manager = kernel.getService<AuthManager>('auth'); |
| 132 | + return { kernel, auth, config: (manager as unknown as { config: CounterConfig }).config }; |
| 133 | +} |
| 134 | + |
| 135 | +const previewCounters = (auth: AuthPlugin): (() => Promise<CounterStore>) => |
| 136 | + (auth as unknown as { invitationPreviewCounters: () => Promise<CounterStore> }).invitationPreviewCounters; |
| 137 | + |
| 138 | +describe('on the composed stack, the auth counters count in a cache registered by factory', () => { |
| 139 | + let kernel: ObjectKernel; |
| 140 | + let auth: AuthPlugin; |
| 141 | + let config: CounterConfig; |
| 142 | + const cache = makeCache(); |
| 143 | + |
| 144 | + beforeAll(async () => { |
| 145 | + ({ kernel, auth, config } = await bootStack([cachePlugin('factory', cache)])); |
| 146 | + }); |
| 147 | + |
| 148 | + afterAll(async () => { |
| 149 | + await kernel?.shutdown().catch(() => undefined); |
| 150 | + }); |
| 151 | + |
| 152 | + it('the rate limiter writes its counter into the registered cache', async () => { |
| 153 | + await expect(config.rateLimitStorage.consume('wiring:first', { window: 10, max: 3 })).resolves.toMatchObject({ allowed: true }); |
| 154 | + expect(await cache.get('wiring:first')).toBeDefined(); |
| 155 | + }); |
| 156 | + |
| 157 | + it('a concurrent burst against one key admits exactly `max` while counting in that cache', async () => { |
| 158 | + const decisions = await Promise.all( |
| 159 | + Array.from({ length: 20 }, () => config.rateLimitStorage.consume('wiring:burst', { window: 10, max: 3 })), |
| 160 | + ); |
| 161 | + expect(decisions.filter((d) => d.allowed)).toHaveLength(3); |
| 162 | + expect(JSON.parse((await cache.get<string>('wiring:burst'))!)).toMatchObject({ n: 20 }); |
| 163 | + }); |
| 164 | + |
| 165 | + it('the OTP send budget and the invitation preview resolve the same cache', async () => { |
| 166 | + await expect(config.sharedCounterStore()).resolves.toBe(cache); |
| 167 | + await expect(previewCounters(auth)()).resolves.toBe(cache); |
| 168 | + }); |
| 169 | +}); |
| 170 | + |
| 171 | +describe("on the composed stack with no cache plugin, the counters keep the bounded per-process store", () => { |
| 172 | + let kernel: ObjectKernel; |
| 173 | + let auth: AuthPlugin; |
| 174 | + let config: CounterConfig; |
| 175 | + |
| 176 | + beforeAll(async () => { |
| 177 | + ({ kernel, auth, config } = await bootStack([])); |
| 178 | + }); |
| 179 | + |
| 180 | + afterAll(async () => { |
| 181 | + await kernel?.shutdown().catch(() => undefined); |
| 182 | + }); |
| 183 | + |
| 184 | + it("the kernel's own `degraded` stand-in is there, and the counters do not count in it", async () => { |
| 185 | + // Control: the kernel really did inject a `cache` — this case is not vacuous. |
| 186 | + const standIn = await kernel.getServiceAsync<unknown>('cache'); |
| 187 | + expect(readServiceSelfInfo(standIn)?.status).toBe('degraded'); |
| 188 | + |
| 189 | + const store = await config.sharedCounterStore(); |
| 190 | + expect(store).toBeInstanceOf(InProcessCounterStore); |
| 191 | + expect(store).not.toBe(standIn); |
| 192 | + await expect(previewCounters(auth)()).resolves.toBeInstanceOf(InProcessCounterStore); |
| 193 | + |
| 194 | + const decisions = await Promise.all( |
| 195 | + Array.from({ length: 20 }, () => config.rateLimitStorage.consume('fallback:burst', { window: 10, max: 3 })), |
| 196 | + ); |
| 197 | + expect(decisions.filter((d) => d.allowed)).toHaveLength(3); |
| 198 | + expect(await (standIn as CounterStore).get('fallback:burst')).toBeUndefined(); |
| 199 | + }); |
| 200 | +}); |
0 commit comments