-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdomain-handler-registry.test.ts
More file actions
360 lines (317 loc) · 19.4 KB
/
Copy pathdomain-handler-registry.test.ts
File metadata and controls
360 lines (317 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* ADR-0076 D11 step ③ (#2462) — the thin domain-handler registry seam.
*
* Two layers under test:
* 1. `DomainHandlerRegistry` matching semantics (first-match, exact vs
* prefix, method restriction) — deliberately faithful to the legacy
* if-chain, rough edges included.
* 2. `HttpDispatcher` integration: the four seeded builtin domains
* (/health /ready /analytics /i18n) behave exactly as their legacy
* if-chain branches did, and `registerDomainHandler` is the public
* seam follow-up domain PRs will use.
*/
import { describe, it, expect, vi } from 'vitest';
import { HttpDispatcher } from './http-dispatcher.js';
import { DomainHandlerRegistry } from './domain-handler-registry.js';
import type { DomainHandler } from './domain-handler-registry.js';
const okHandler = (tag: string): DomainHandler =>
async () => ({ handled: true, response: { status: 200, body: { tag } } });
/** Minimal kernel: objectql + optional extra services. */
function makeKernel(services: Record<string, any> = {}, state = 'running') {
const objectql = {
find: vi.fn().mockResolvedValue([]),
getObjects: vi.fn().mockReturnValue({}),
registry: { getObject: vi.fn().mockReturnValue(null), getRegisteredTypes: vi.fn().mockReturnValue([]) },
};
const all: Record<string, any> = { objectql, ...services };
const kernel: any = {
getState: () => state,
getService: (name: string) => all[name] ?? null,
getServiceAsync: async (name: string) => all[name] ?? null,
context: { getService: (name: string) => all[name] ?? null },
};
return kernel;
}
function makeDispatcher(services: Record<string, any> = {}, state = 'running') {
return new HttpDispatcher(makeKernel(services, state), undefined, {
enforceProjectMembership: false,
});
}
// ---------------------------------------------------------------------------
// DomainHandlerRegistry matching semantics
// ---------------------------------------------------------------------------
describe('DomainHandlerRegistry', () => {
it('resolves in registration order, first match wins', () => {
const registry = new DomainHandlerRegistry();
const first = okHandler('first');
const second = okHandler('second');
registry.register({ prefix: '/a', handler: first });
registry.register({ prefix: '/a', handler: second });
expect(registry.resolve('/a/x', 'GET')?.handler).toBe(first);
});
it("match: 'exact' does not claim sub-paths; default prefix match does (legacy startsWith, rough edges included)", () => {
const registry = new DomainHandlerRegistry();
registry.register({ prefix: '/health', match: 'exact', handler: okHandler('h') });
registry.register({ prefix: '/i18n', handler: okHandler('i') });
expect(registry.resolve('/health', 'GET')).toBeDefined();
expect(registry.resolve('/health/deep', 'GET')).toBeUndefined();
expect(registry.resolve('/i18n/locales', 'GET')).toBeDefined();
// Faithful legacy semantics: bare startsWith also matches '/i18nxx'.
expect(registry.resolve('/i18nxx', 'GET')).toBeDefined();
});
it('restricts by method when `methods` is set (case-insensitive on input)', () => {
const registry = new DomainHandlerRegistry();
registry.register({ prefix: '/health', match: 'exact', methods: ['GET'], handler: okHandler('h') });
expect(registry.resolve('/health', 'get')).toBeDefined();
expect(registry.resolve('/health', 'POST')).toBeUndefined();
});
it('rejects a prefix that does not start with a slash', () => {
const registry = new DomainHandlerRegistry();
expect(() => registry.register({ prefix: 'health', handler: okHandler('h') })).toThrow(/prefix/);
});
});
// ---------------------------------------------------------------------------
// Dispatcher integration — seeded builtin domains keep legacy behavior
// ---------------------------------------------------------------------------
describe('HttpDispatcher domain registry (D11 step ③)', () => {
it('GET /health serves the liveness payload', async () => {
const result = await makeDispatcher().dispatch('GET', '/health', undefined, {}, {} as any);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body?.data?.status).toBe('ok');
});
it('GET /ready reflects kernel state: running → 200, booting → 503', async () => {
const ready = await makeDispatcher({}, 'running').dispatch('GET', '/ready', undefined, {}, {} as any);
expect(ready.response?.status).toBe(200);
expect(ready.response?.body?.data?.state).toBe('running');
const booting = await makeDispatcher({}, 'initializing').dispatch('GET', '/ready', undefined, {}, {} as any);
expect(booting.response?.status).toBe(503);
expect(booting.response?.body?.error?.details?.state).toBe('initializing');
});
it('non-GET /health is NOT claimed by the health domain (falls through the legacy chain)', async () => {
const result = await makeDispatcher().dispatch('POST', '/health', undefined, {}, {} as any);
// Same as before the registry: no branch claims POST /health.
expect(result.response?.status ?? 404).not.toBe(200);
});
it('/i18n keeps its in-handler 501 when the i18n service is absent', async () => {
const result = await makeDispatcher().dispatch('GET', '/i18n/locales', undefined, {}, {} as any);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(501);
});
it('/i18n/locales serves from the i18n service when present', async () => {
const i18n = { getLocales: vi.fn().mockReturnValue(['en', 'zh-CN']), getTranslations: vi.fn().mockReturnValue({}) };
const result = await makeDispatcher({ i18n }).dispatch('GET', '/i18n/locales', undefined, {}, {} as any);
expect(result.response?.status).toBe(200);
expect(result.response?.body?.data?.locales).toEqual(['en', 'zh-CN']);
});
it('/analytics bridges to the analytics service exactly as the legacy branch did', async () => {
const analytics = {
query: vi.fn().mockResolvedValue({ rows: [{ n: 1 }] }),
analyticsQuery: vi.fn().mockResolvedValue({ rows: [{ n: 1 }] }),
};
const result = await makeDispatcher({ analytics }).dispatch(
'POST', '/analytics/query', { metric: 'count' }, {}, {} as any,
);
expect(result.handled).toBe(true);
// The bridge consulted the service (whichever entry point it uses).
expect(
analytics.query.mock.calls.length + analytics.analyticsQuery.mock.calls.length,
).toBeGreaterThan(0);
});
it('registerDomainHandler is the public seam: a service-owned domain resolves before the legacy chain', async () => {
const dispatcher = makeDispatcher();
const handler = vi.fn(async (req: any) => ({
handled: true as const,
response: { status: 200, body: { echo: req.path } },
}));
dispatcher.registerDomainHandler({ prefix: '/custom-domain', handler });
const result = await dispatcher.dispatch('GET', '/custom-domain/thing', undefined, { q: '1' }, {} as any);
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0][0]).toMatchObject({ path: '/custom-domain/thing', method: 'GET' });
expect(result.response?.body?.echo).toBe('/custom-domain/thing');
});
});
// ---------------------------------------------------------------------------
// PR-2 — segment matching + extracted notification/security domains
// ---------------------------------------------------------------------------
describe('DomainHandlerRegistry segment matching (PR-2)', () => {
it("match: 'segment' claims the prefix and slash-separated sub-paths, but not lexical extensions", () => {
const registry = new DomainHandlerRegistry();
registry.register({ prefix: '/security', match: 'segment', handler: okHandler('s') });
expect(registry.resolve('/security', 'GET')).toBeDefined();
expect(registry.resolve('/security/suggested-bindings', 'GET')).toBeDefined();
// The legacy `=== p || startsWith(p + '/')` shape: '/securityfoo' is NOT claimed.
expect(registry.resolve('/securityfoo', 'GET')).toBeUndefined();
});
});
describe('HttpDispatcher extracted domains (PR-2)', () => {
it('/notifications requires an authenticated user (401) when the service is wired', async () => {
const notification = { listInbox: vi.fn().mockResolvedValue([]), markRead: vi.fn(), markAllRead: vi.fn() };
const result = await makeDispatcher({ notification }).dispatch('GET', '/notifications', undefined, {}, {} as any);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(401);
});
it('/notifications lists the inbox for an authenticated user (thin delegate carries the extracted body)', async () => {
const notification = { listInbox: vi.fn().mockResolvedValue([{ id: 'n1' }]), markRead: vi.fn(), markAllRead: vi.fn() };
// Call the public delegate directly: dispatch() re-resolves identity
// from the (mock, auth-less) kernel and would overwrite the seeded
// executionContext with an anonymous one.
const context: any = { executionContext: { userId: 'u1' } };
const result = await makeDispatcher({ notification }).handleNotification('', 'GET', undefined, { limit: '5' }, context);
expect(result.response?.status).toBe(200);
expect(notification.listInbox).toHaveBeenCalledWith('u1', expect.objectContaining({ limit: 5 }));
});
it('/notifications tolerates redundant slashes in the sub-path (split+filter, CodeQL redos fix)', async () => {
const notification = { listInbox: vi.fn(), markRead: vi.fn().mockResolvedValue({ updated: 1 }), markAllRead: vi.fn() };
const context: any = { executionContext: { userId: 'u1' } };
const result = await makeDispatcher({ notification }).handleNotification('//read//', 'POST', { ids: ['n1'] }, {}, context);
expect(result.response?.status).toBe(200);
expect(notification.markRead).toHaveBeenCalledWith('u1', ['n1']);
});
it('/security responds 503 when no security service is wired (legacy in-handler semantics)', async () => {
const result = await makeDispatcher().dispatch('GET', '/security/suggested-bindings', undefined, {}, {} as any);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(503);
});
it('/security denies anonymous callers unconditionally when the service is wired', async () => {
const security = {
listAudienceBindingSuggestions: vi.fn().mockResolvedValue([]),
confirmAudienceBindingSuggestion: vi.fn(),
dismissAudienceBindingSuggestion: vi.fn(),
};
const result = await makeDispatcher({ security }).dispatch('GET', '/security/suggested-bindings', undefined, {}, {} as any);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(401);
expect(security.listAudienceBindingSuggestions).not.toHaveBeenCalled();
});
it('/security lists suggestions for an authenticated caller (thin delegate carries the extracted body)', async () => {
const security = {
listAudienceBindingSuggestions: vi.fn().mockResolvedValue([{ id: 's1' }]),
confirmAudienceBindingSuggestion: vi.fn(),
dismissAudienceBindingSuggestion: vi.fn(),
};
// Direct delegate call for the same reason as the notifications case.
const context: any = { executionContext: { userId: 'admin-1' } };
const result = await makeDispatcher({ security }).handleSecurity('/suggested-bindings', 'GET', undefined, { status: 'open' }, context);
expect(result.response?.status).toBe(200);
expect(security.listAudienceBindingSuggestions).toHaveBeenCalledWith(
expect.objectContaining({ userId: 'admin-1' }),
expect.objectContaining({ status: 'open' }),
);
});
it('/securityfoo is NOT claimed by the security domain (segment semantics preserved from the if-chain)', async () => {
const security = { listAudienceBindingSuggestions: vi.fn() };
const result = await makeDispatcher({ security }).dispatch('GET', '/securityfoo', undefined, {}, {} as any);
expect(security.listAudienceBindingSuggestions).not.toHaveBeenCalled();
expect(result.response?.status ?? 404).not.toBe(200);
});
});
// ---------------------------------------------------------------------------
// PR-3 — keys / storage / ui extraction
// ---------------------------------------------------------------------------
describe('HttpDispatcher extracted domains (PR-3: keys/storage/ui)', () => {
it('POST /keys rejects anonymous callers with 401 (identity gate inside the extracted body)', async () => {
const result = await makeDispatcher().dispatch('POST', '/keys', { name: 'k' }, {}, {} as any);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(401);
});
it('GET /keys answers 405 (mint is POST-only), and /keysfoo is NOT claimed (segment semantics)', async () => {
const dispatcher = makeDispatcher();
const wrongMethod = await dispatcher.dispatch('GET', '/keys', undefined, {}, {} as any);
expect(wrongMethod.response?.status).toBe(405);
const lexical = await dispatcher.dispatch('POST', '/keysfoo', { name: 'k' }, {}, {} as any);
expect(lexical.response?.status ?? 404).not.toBe(405);
});
it('POST /keys mints a key pinned to the caller (thin delegate carries the extracted body)', async () => {
const insert = vi.fn().mockResolvedValue({ id: 'key-row-1' });
const objectql = {
insert,
find: vi.fn().mockResolvedValue([]),
getObjects: vi.fn().mockReturnValue({}),
registry: { getObject: vi.fn().mockReturnValue(null), getRegisteredTypes: vi.fn().mockReturnValue([]) },
};
const context: any = { executionContext: { userId: 'caller-1' } };
// Direct delegate call — dispatch() would re-resolve identity off the
// auth-less mock kernel and overwrite the seeded executionContext.
const result = await makeDispatcher({ objectql }).handleKeys('POST', { name: 'CI Key', user_id: 'attacker' }, context);
expect(result.response?.status).toBe(201);
const row = insert.mock.calls[0][1];
expect(insert.mock.calls[0][0]).toBe('sys_api_key');
// user_id pinned to caller; body's user_id ignored; only the hash stored.
expect(row.user_id).toBe('caller-1');
expect(row.key).not.toBe(result.response?.body?.data?.key);
expect(result.response?.body?.data?.key).toBeTruthy();
});
it('/storage responds 501 when file-storage is not configured (extracted body keeps in-handler semantics)', async () => {
const result = await makeDispatcher().dispatch('POST', '/storage/upload', { blob: 1 }, {}, {} as any);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(501);
});
it('/storage/upload uploads through the file-storage service', async () => {
const upload = vi.fn().mockResolvedValue({ id: 'f1' });
const result = await makeDispatcher({ 'file-storage': { upload, download: vi.fn() } })
.dispatch('POST', '/storage/upload', { some: 'file' }, {}, {} as any);
expect(result.response?.status).toBe(200);
expect(upload).toHaveBeenCalledTimes(1);
});
it('/ui/view/:object serves the protocol getUiView result; 503 without a protocol service', async () => {
const getUiView = vi.fn().mockResolvedValue({ view: 'list-def' });
const ok = await makeDispatcher({ protocol: { getUiView } }).dispatch('GET', '/ui/view/account/list', undefined, {}, {} as any);
expect(ok.response?.status).toBe(200);
expect(getUiView).toHaveBeenCalledWith({ object: 'account', type: 'list' });
const missing = await makeDispatcher().dispatch('GET', '/ui/view/account', undefined, {}, {} as any);
expect(missing.response?.status).toBe(503);
});
});
// ---------------------------------------------------------------------------
// PR-4 — share-links extraction
// ---------------------------------------------------------------------------
describe('HttpDispatcher extracted domains (PR-4: share-links)', () => {
it('/share-links responds 501 when the shareLinks service is absent', async () => {
const result = await makeDispatcher().dispatch('GET', '/share-links', undefined, {}, {} as any);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(501);
});
it('/share-linksfoo is NOT claimed (segment semantics)', async () => {
const shareLinks = { resolveToken: vi.fn(), createLink: vi.fn(), listLinks: vi.fn(), revokeLink: vi.fn() };
const result = await makeDispatcher({ shareLinks }).dispatch('GET', '/share-linksfoo', undefined, {}, {} as any);
expect(shareLinks.listLinks).not.toHaveBeenCalled();
expect(result.response?.status ?? 404).not.toBe(501);
});
it('management routes reject anonymous callers with UNAUTHENTICATED', async () => {
const shareLinks = { resolveToken: vi.fn(), createLink: vi.fn(), listLinks: vi.fn(), revokeLink: vi.fn() };
const result = await makeDispatcher({ shareLinks })
.handleShareLinks('', 'POST', { object: 'account', recordId: 'r1' }, {}, {} as any);
expect(result.response?.status).toBe(401);
expect(result.response?.body?.error?.details?.code).toBe('UNAUTHENTICATED');
});
it('public resolve route serves the record through the request-kernel engine with redaction', async () => {
const resolveToken = vi.fn().mockResolvedValue({
link: { id: 'l1', token: 't1', object_name: 'account', record_id: 'r1', permission: 'view', audience: 'anyone' },
redactFields: ['secret'],
});
const find = vi.fn().mockResolvedValue([{ id: 'r1', name: 'Acme', secret: 'hide-me' }]);
const dispatcher = makeDispatcher({
shareLinks: { resolveToken },
objectql: {
find,
getObjects: vi.fn().mockReturnValue({}),
registry: { getObject: vi.fn().mockReturnValue(null), getRegisteredTypes: vi.fn().mockReturnValue([]) },
},
});
const result = await dispatcher.handleShareLinks('/t1/resolve', 'GET', undefined, {}, {} as any);
expect(result.response?.status).toBe(200);
const record = result.response?.body?.data?.record;
expect(record?.name).toBe('Acme');
// redactFields stripped before the record leaves the server.
expect(record?.secret).toBeUndefined();
});
it('unmatched sub-path returns the standard ROUTE_NOT_FOUND envelope', async () => {
const shareLinks = { resolveToken: vi.fn(), createLink: vi.fn(), listLinks: vi.fn(), revokeLink: vi.fn() };
const context: any = { executionContext: { userId: 'u1' } };
const result = await makeDispatcher({ shareLinks }).handleShareLinks('/a/b/c', 'GET', undefined, {}, context);
expect(result.response?.status).toBe(404);
expect(result.response?.body?.error?.type).toBe('ROUTE_NOT_FOUND');
});
});