-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathapi-endpoint-step.test.ts
More file actions
606 lines (532 loc) · 28.1 KB
/
Copy pathapi-endpoint-step.test.ts
File metadata and controls
606 lines (532 loc) · 28.1 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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* The endpoint dispatch step in isolation (#5040 E3 / #5090).
*
* Every case here is about ONE question: when does this step answer, and when
* does it write nothing so the transport's existing unmatched answer stands?
* Getting that wrong in either direction is a live behavior change — and since
* the #5040 E7 publish flip it is live for real traffic, not just in principle:
* endpoints can be declared, so a step that answers when it should stay silent
* now shadows the transport's 404 on a deployment.
*
* `matchEndpoint` is driven by a stub implementing the contract in
* `@objectstack/spec/contracts` — deliberately, not by the real matcher: that
* implementation is #5089, developed in parallel, and this seam must not depend
* on its landing order (nor its absence be untested — probe-absent is the
* passthrough case below).
*/
import { describe, it, expect } from 'vitest';
import { ApiEndpointSchema, type ApiEndpoint } from '@objectstack/spec/api';
import type { ApiEndpointMatch } from '@objectstack/spec/contracts';
import type { CounterStore } from '@objectstack/plugin-auth/rate-limit-storage';
import {
APP_ENDPOINT_SEGMENT,
appEndpointMountPrefix,
isAppEndpointPath,
runAppEndpointStep,
type AppEndpointExecutionInput,
} from './api-endpoint-step.js';
import {
createEndpointRateLimiterRegistry,
endpointBucketKey,
type EndpointPolicyContext,
} from './endpoint-policy.js';
/** A declared endpoint in the ADR-0121 D1 shape, defaults materialized. */
const TASKS: ApiEndpoint = ApiEndpointSchema.parse({
name: 'showcase_tasks',
path: '/api/v1/apps/showcase/tasks',
method: 'GET',
type: 'object_operation',
target: 'showcase_task',
objectParams: { object: 'showcase_task', operation: 'find' },
});
/** A metadata service that owns exactly the endpoints it is given. */
function matcherFor(endpoints: ApiEndpoint[]) {
const calls: Array<{ path: string; method: string }> = [];
return {
calls,
service: {
matchEndpoint: async (query: { path: string; method: string }): Promise<ApiEndpointMatch | undefined> => {
calls.push(query);
const hit = endpoints.find(
(e) => e.path === query.path.replace(/\/$/, '') && e.method === query.method.toUpperCase(),
);
return hit ? { endpoint: hit, params: {} } : undefined;
},
},
};
}
const step = (path: string, method = 'GET', service?: unknown) =>
runAppEndpointStep({ method, path, prefix: '/api/v1', metadataService: service as never });
describe('the mount prefix is spelled once (ADR-0121 D1)', () => {
it('is `<prefix>/apps/`, trailing slash included', () => {
expect(APP_ENDPOINT_SEGMENT).toBe('apps');
expect(appEndpointMountPrefix('/api/v1')).toBe('/api/v1/apps/');
expect(appEndpointMountPrefix('/api/v1/')).toBe('/api/v1/apps/');
expect(appEndpointMountPrefix('/custom')).toBe('/custom/apps/');
});
it('scopes by segment, not by string prefix', () => {
expect(isAppEndpointPath('/api/v1/apps/showcase/tasks', '/api/v1')).toBe(true);
expect(isAppEndpointPath('/api/v1/apps/a', '/api/v1')).toBe(true);
// The bare mount itself declares nothing — and `appsx` is a different
// word, which a `startsWith('/api/v1/apps')` test would have missed.
expect(isAppEndpointPath('/api/v1/apps/', '/api/v1')).toBe(false);
expect(isAppEndpointPath('/api/v1/apps', '/api/v1')).toBe(false);
expect(isAppEndpointPath('/api/v1/appsx/thing', '/api/v1')).toBe(false);
expect(isAppEndpointPath('/api/v1/data/showcase_task', '/api/v1')).toBe(false);
// A deployment on a non-default prefix scopes to ITS prefix only.
expect(isAppEndpointPath('/api/v1/apps/showcase/tasks', '/custom')).toBe(false);
});
});
describe('the step writes nothing unless a declaration owns the request', () => {
it('never asks about a path outside the mount', async () => {
const { service, calls } = matcherFor([TASKS]);
expect(await step('/api/v1/data/showcase_task', 'GET', service)).toBeUndefined();
expect(await step('/api/v1/health', 'GET', service)).toBeUndefined();
expect(await step('/nope', 'GET', service)).toBeUndefined();
expect(calls, 'the metadata service was consulted for a non-endpoint path').toEqual([]);
});
it('passes through when the kernel has no metadata service', async () => {
expect(await step('/api/v1/apps/showcase/tasks', 'GET', undefined)).toBeUndefined();
});
it('passes through when the metadata service carries no matchEndpoint (#5089 not landed)', async () => {
// The contract's own probe convention: an occupant of the slot with no
// endpoint index simply omits the member. That must be a fully working
// passthrough, not a crash and not a 501.
const withoutMatcher = { get: async () => undefined, list: async () => [] };
expect(await step('/api/v1/apps/showcase/tasks', 'GET', withoutMatcher)).toBeUndefined();
});
it('passes through on a miss', async () => {
const { service, calls } = matcherFor([TASKS]);
expect(await step('/api/v1/apps/showcase/unknown', 'GET', service)).toBeUndefined();
// Method is part of the identity: the same path under another verb is a
// different endpoint, and a miss.
expect(await step('/api/v1/apps/showcase/tasks', 'DELETE', service)).toBeUndefined();
expect(calls).toEqual([
{ path: '/api/v1/apps/showcase/unknown', method: 'GET' },
{ path: '/api/v1/apps/showcase/tasks', method: 'DELETE' },
]);
});
it('lets a matcher failure propagate — an outage must not read as a 404', async () => {
const broken = { matchEndpoint: async () => { throw new Error('metadata store unreachable'); } };
await expect(step('/api/v1/apps/showcase/tasks', 'GET', broken)).rejects.toThrow('metadata store unreachable');
});
});
describe('a match with no wiring answers an honest 501', () => {
it('reports NOT_IMPLEMENTED in the declared error envelope', async () => {
const { service } = matcherFor([TASKS]);
const answer = await step('/api/v1/apps/showcase/tasks', 'GET', service);
expect(answer?.status).toBe(501);
const body = answer!.body as { success: boolean; error: Record<string, unknown> };
expect(body.success).toBe(false);
expect(body.error.code).toBe('NOT_IMPLEMENTED');
expect(body.error.httpStatus).toBe(501);
// Names the endpoint it matched and says plainly that nothing ran —
// "matched but not executed" must never read as "executed and empty".
expect(body.error.message).toContain('showcase_tasks');
expect(body.error.message).toContain('no wiring');
expect(String(body.error.hint)).toContain('#5040');
});
it('passes the request coordinates through untouched', async () => {
const { service, calls } = matcherFor([TASKS]);
await step('/api/v1/apps/showcase/tasks', 'GET', service);
// No normalization here: `matchEndpoint`'s contract owns trailing-slash
// trimming and case folding, and a second, weaker copy in the consumer
// is how two spellings of "the same path" start to disagree.
expect(calls).toEqual([{ path: '/api/v1/apps/showcase/tasks', method: 'GET' }]);
});
it('names the keys it did NOT evaluate when no policy context was threaded', async () => {
// Truthfulness of the report is the point: this seam's whole job today
// is telling an operator what did and did not happen.
const { service } = matcherFor([TASKS]);
const answer = await step('/api/v1/apps/showcase/tasks', 'GET', service);
const hint = String((answer!.body as { error: { hint: unknown } }).error.hint);
expect(hint).toContain('not evaluated');
expect(hint).toContain('authRequired');
expect(answer!.headers).toBeUndefined();
});
});
/**
* The policy chain, seen from the step (#5040 E4 / #5091).
*
* The module-level cases live in `endpoint-policy.test.ts`; what is asserted
* here is the WIRING — that the chain runs between the match and the answer,
* that a denial short-circuits (no 501, no execution slot reached), and that a
* pass still ends in the 501 until E5 lands.
*/
describe('the policy chain runs between the match and the answer', () => {
/** An endpoint that is open to anonymous callers unless a case says otherwise. */
const OPEN: ApiEndpoint = ApiEndpointSchema.parse({
...TASKS, name: 'showcase_open', authRequired: false,
});
function policyContext(overrides: Partial<EndpointPolicyContext> = {}): EndpointPolicyContext {
const entries = new Map<string, unknown>();
const store: CounterStore = {
get: async <T,>(key: string) => entries.get(key) as T | undefined,
set: async (key: string, value: unknown) => { entries.set(key, value); },
};
return {
limiters: createEndpointRateLimiterRegistry({ resolveCache: async () => store }),
...overrides,
};
}
const policedStep = (endpoints: ApiEndpoint[], policy: EndpointPolicyContext, method = 'GET') =>
runAppEndpointStep({
method,
path: endpoints[0]!.path,
prefix: '/api/v1',
metadataService: matcherFor(endpoints).service as never,
policy,
});
it('answers 401 instead of 501 when the endpoint requires auth and the caller has none', async () => {
const answer = await policedStep([TASKS], policyContext());
expect(answer?.status).toBe(401);
const body = answer!.body as { success: boolean; error: Record<string, unknown> };
expect(body.error.code).toBe('UNAUTHENTICATED');
// The 501 is NOT also emitted: a denial is the answer, not a stage.
expect(JSON.stringify(body)).not.toContain('NOT_IMPLEMENTED');
});
it('answers 429 with the Retry-After header once the endpoint budget is spent', async () => {
const limited = ApiEndpointSchema.parse({
...OPEN, name: 'showcase_limited', rateLimit: { enabled: true, windowMs: 1_000, maxRequests: 1 },
});
const policy = policyContext();
expect((await policedStep([limited], policy))?.status).toBe(501); // within budget
const over = await policedStep([limited], policy);
expect(over?.status).toBe(429);
// The header rides on the ANSWER, so the transport writes it with the
// body — a 429 whose Retry-After got lost tells a client nothing.
expect(over?.headers).toEqual({ 'Retry-After': '1' });
expect((over!.body as { error: { code: string } }).error.code).toBe('RATE_LIMIT_EXCEEDED');
});
it('reaches the 501 only after the chain passed, and says so', async () => {
const answer = await policedStep([OPEN], policyContext());
expect(answer?.status).toBe(501);
const hint = String((answer!.body as { error: { hint: unknown } }).error.hint);
expect(hint).toContain('enforced');
expect(hint).toContain('#5040');
});
it('never puts the cacheTtl header on the 501 — but the verdict still carries it', async () => {
// Exposure, not application: `Cache-Control` describes a successful body
// that does not exist yet (execution is E5), and telling a client to
// cache a 501 for 30s would be worse than saying nothing. The header
// lives on the policy verdict, which is what the executor will read —
// asserted directly in `endpoint-policy.test.ts`.
const cached = ApiEndpointSchema.parse({ ...OPEN, name: 'showcase_cached', cacheTtl: 30 });
const answer = await policedStep([cached], policyContext());
expect(answer?.status).toBe(501);
expect(answer?.headers).toBeUndefined();
});
it('resolves the caller once and keys the endpoint bucket with it', async () => {
const seen: Array<Record<string, unknown>> = [];
const entries = new Map<string, unknown>();
const store: CounterStore = {
get: async <T,>(k: string) => entries.get(k) as T | undefined,
set: async (k: string, v: unknown) => { entries.set(k, v); },
};
const limited = ApiEndpointSchema.parse({
...TASKS, name: 'showcase_tasks', rateLimit: { enabled: true, windowMs: 1_000, maxRequests: 5 },
});
const answer = await policedStep([limited], {
limiters: createEndpointRateLimiterRegistry({ resolveCache: async () => store }),
headers: { cookie: 'session=abc' },
remoteAddress: '203.0.113.9',
resolvePrincipalId: async (headers) => { seen.push(headers); return 'usr_7'; },
});
// Authenticated, so the 401 gate passes and the bucket keys by principal
// rather than by address — one lookup serving both.
expect(answer?.status).toBe(501);
expect(seen).toEqual([{ cookie: 'session=abc' }]);
expect([...entries.keys()]).toEqual([endpointBucketKey('showcase_tasks', 'principal:usr_7')]);
});
});
/**
* Execution, wired to the far side of the policy chain (#5040 E5b / #5129).
*
* The delegation itself is `endpoint-executor.test.ts`'s subject; what is
* asserted here is the JOIN — that a passing request reaches the executor with
* the request's own coordinates and identity, that a denial never does, and
* that `cacheTtl`'s header lands on a success and on nothing else.
*/
describe('execution runs on the far side of the policy chain', () => {
const OPEN: ApiEndpoint = ApiEndpointSchema.parse({ ...TASKS, name: 'showcase_open', authRequired: false });
const limiters = () => createEndpointRateLimiterRegistry({ resolveCache: async () => undefined });
/** Records every delegated `callData` call and answers with a stub result. */
function callDataSpy(result: unknown = { object: 'showcase_task', records: [], total: 0 }) {
const calls: unknown[][] = [];
return {
calls,
fn: async (...args: unknown[]) => { calls.push(args); return result; },
};
}
const wiredStep = (
endpoints: ApiEndpoint[],
execution: Partial<AppEndpointExecutionInput> & { deps: AppEndpointExecutionInput['deps'] },
policy: Partial<EndpointPolicyContext> = {},
method = 'GET',
) => runAppEndpointStep({
method,
path: endpoints[0]!.path,
prefix: '/api/v1',
metadataService: matcherFor(endpoints).service as never,
policy: { limiters: limiters(), ...policy },
execution: {
request: {
method,
path: endpoints[0]!.path,
query: { limit: '5' },
headers: { 'x-caller': 'integration' },
body: undefined,
},
...execution,
},
});
it('delegates a passing request with the request\'s own identity envelope', async () => {
const spy = callDataSpy();
const executionContext = { userId: 'usr_7', isSystem: false } as never;
const answer = await wiredStep([OPEN], {
deps: { callData: spy.fn as never },
executionContext,
environmentId: 'env_1',
dataDriver: { driver: true },
});
expect(answer?.status).toBe(200);
expect(answer?.body).toEqual({
success: true,
data: { object: 'showcase_task', records: [], total: 0 },
meta: undefined,
});
// The identity envelope, the driver and the scope ride on the delegated
// call — #5040 §4's red line, and the exact thing #4936's dead branch
// dropped (it would have read as `system`, RLS bypassed).
expect(spy.calls).toEqual([[
'query',
{ object: 'showcase_task', query: { limit: '5' } },
{ driver: true },
'env_1',
executionContext,
]]);
});
it('puts the cacheTtl Cache-Control on a SUCCESS answer', async () => {
const cached = ApiEndpointSchema.parse({ ...OPEN, name: 'showcase_cached', cacheTtl: 30 });
const answer = await wiredStep([cached], { deps: { callData: callDataSpy().fn as never } });
expect(answer?.status).toBe(200);
expect(answer?.headers).toEqual({ 'Cache-Control': 'private, max-age=30' });
});
it('never puts it on an ERROR answer, however the failure arose', async () => {
const cached = ApiEndpointSchema.parse({ ...OPEN, name: 'showcase_cached', cacheTtl: 30 });
// A delegated pipeline that throws — the executor maps it to a 4xx/5xx
// answer, and a client must not be told to reuse a failure for 30s.
const answer = await wiredStep([cached], {
deps: { callData: async () => { throw { statusCode: 404, message: 'no such object' }; } },
});
expect(answer?.status).toBe(404);
expect(answer?.headers).toBeUndefined();
// Same for a declaration this runtime does not execute (501 from the
// executor's own `unsupported` arm, not from the no-wiring branch).
const proxied = ApiEndpointSchema.parse({
...OPEN, name: 'showcase_proxy', type: 'proxy', target: 'https://example.invalid', cacheTtl: 30,
});
const unsupported = await wiredStep([proxied], { deps: { callData: async () => ({}) } });
expect(unsupported?.status).toBe(501);
expect(unsupported?.headers).toBeUndefined();
expect(String((unsupported!.body as { error: { message: string } }).error.message)).toContain('proxy');
});
it('never reaches the executor when a policy denied the request', async () => {
const spy = callDataSpy();
// `TASKS` keeps the default `authRequired: true`; the caller is anonymous.
const answer = await wiredStep([TASKS], { deps: { callData: spy.fn as never } });
expect(answer?.status).toBe(401);
expect(spy.calls, 'the executor ran for a request the policy chain denied').toEqual([]);
});
it('answers an honest 501 when a caller wired policies but no executor', async () => {
const answer = await runAppEndpointStep({
method: 'GET',
path: OPEN.path,
prefix: '/api/v1',
metadataService: matcherFor([OPEN]).service as never,
policy: { limiters: limiters() },
});
expect(answer?.status).toBe(501);
const hint = String((answer!.body as { error: { hint: unknown } }).error.hint);
expect(hint).toContain('enforced');
expect(hint).toContain('no execution wiring');
});
});
/**
* The mapping keys, joined to the chain (#5040 E5c / #5137).
*
* `api-mapping.test.ts` owns what a projection IS; what is asserted here is
* where it applies — that a mapped body is what the executor delegates, that a
* mapped result is what the caller receives, that an ERROR answer is never
* remapped whatever produced it, and that a declaration this runtime cannot
* serve is refused before the target runs rather than after.
*/
describe('the mapping keys apply on the two sides of the delegation', () => {
const CREATE: ApiEndpoint = ApiEndpointSchema.parse({
name: 'showcase_inquiries',
path: '/api/v1/apps/showcase/inquiries',
method: 'POST',
type: 'object_operation',
target: 'showcase_inquiry',
objectParams: { object: 'showcase_inquiry', operation: 'create' },
authRequired: false,
});
const limiters = () => createEndpointRateLimiterRegistry({ resolveCache: async () => undefined });
function callDataSpy(result: unknown = { id: 'rec_1', name: 'Ada', internal_note: 'do not ship' }) {
const calls: unknown[][] = [];
return { calls, fn: async (...args: unknown[]) => { calls.push(args); return result; } };
}
const mappedStep = (
endpoint: ApiEndpoint,
callData: unknown,
body: unknown = { firstName: 'Ada', secret: 'internal' },
policy: Partial<EndpointPolicyContext> = {},
) => runAppEndpointStep({
method: endpoint.method,
path: endpoint.path,
prefix: '/api/v1',
metadataService: matcherFor([endpoint]).service as never,
policy: { limiters: limiters(), ...policy },
execution: {
request: { method: endpoint.method, path: endpoint.path, query: { trace: '1' }, body },
deps: { callData: callData as never },
},
});
it('delegates the MAPPED body — the executor never sees the raw one', async () => {
const spy = callDataSpy();
const mapped = ApiEndpointSchema.parse({
...CREATE,
inputMapping: [{ source: 'firstName', target: 'first_name' }],
});
const answer = await mappedStep(mapped, spy.fn);
expect(answer?.status).toBe(201);
// `data` is the projection: the renamed field is there and the
// undeclared one is gone, delegated through the same `callData` shape
// `/data` uses.
expect(spy.calls).toEqual([['create', { object: 'showcase_inquiry', data: { first_name: 'Ada' } }, undefined, undefined, undefined]]);
});
it('leaves the query string alone — inputMapping maps the BODY', async () => {
// The vocabulary says "Map Request Body to Internal Params"; query
// parameters keep reaching the pipeline exactly as they did before.
const spy = callDataSpy({ records: [], total: 0 });
const find = ApiEndpointSchema.parse({
...CREATE,
name: 'showcase_find',
method: 'GET',
objectParams: { object: 'showcase_inquiry', operation: 'find' },
inputMapping: [{ source: 'firstName', target: 'first_name' }],
});
await mappedStep(find, spy.fn);
expect((spy.calls[0]![1] as { query: unknown }).query).toEqual({ trace: '1' });
});
it('delegates the caller\'s own body when no mapping is declared', async () => {
const spy = callDataSpy();
const body = { firstName: 'Ada', secret: 'internal' };
await mappedStep(CREATE, spy.fn, body);
// By reference: an endpoint that declares no mapping is served exactly
// as E5b served it, with no projection in between.
expect((spy.calls[0]![1] as { data: unknown }).data).toBe(body);
});
it('answers with the MAPPED result on a success', async () => {
const spy = callDataSpy();
const mapped = ApiEndpointSchema.parse({
...CREATE,
outputMapping: [{ source: 'id', target: 'inquiry_id' }, { source: 'name', target: 'contact.name' }],
});
const answer = await mappedStep(mapped, spy.fn);
expect(answer?.status).toBe(201);
expect(answer?.body).toEqual({
success: true,
data: { inquiry_id: 'rec_1', contact: { name: 'Ada' } },
meta: undefined,
});
// The allow-list property, end to end: an internal field the pipeline
// returned and the declaration did not name never reaches the wire.
expect(JSON.stringify(answer?.body)).not.toContain('internal_note');
});
it('keeps the cacheTtl header on a mapped success', async () => {
// `cacheTtl` is GET-only (#5040 §3.3), so this is a read endpoint: the
// point is that the two keys compose — the projection replaces the body
// and the policy verdict's header still rides with it.
const mapped = ApiEndpointSchema.parse({
...CREATE,
name: 'showcase_cached_map',
method: 'GET',
objectParams: { object: 'showcase_inquiry', operation: 'find' },
cacheTtl: 30,
outputMapping: [{ source: 'total', target: 'count' }],
});
const answer = await mappedStep(mapped, callDataSpy({ records: [], total: 2 }).fn);
expect(answer?.body).toEqual({ success: true, data: { count: 2 }, meta: undefined });
expect(answer?.headers).toEqual({ 'Cache-Control': 'private, max-age=30' });
});
it('never remaps an ERROR answer — a mapping must not disguise a failure', async () => {
const outputMapping = [{ source: 'id', target: 'inquiry_id' }];
// 401: denied by the policy chain, before execution.
const authed = ApiEndpointSchema.parse({ ...CREATE, name: 'showcase_authed', authRequired: true, outputMapping });
const denied = await mappedStep(authed, callDataSpy().fn);
expect(denied?.status).toBe(401);
expect((denied!.body as { error: { code: string } }).error.code).toBe('UNAUTHENTICATED');
// 400: a delegated pipeline's own failure.
const failing = ApiEndpointSchema.parse({ ...CREATE, name: 'showcase_failing', outputMapping });
const bad = await mappedStep(failing, async () => { throw { statusCode: 400, message: 'name is required' }; });
expect(bad?.status).toBe(400);
expect((bad!.body as { error: { message: string } }).error.message).toBe('name is required');
// 501: a declaration this runtime does not execute.
const proxied = ApiEndpointSchema.parse({
...CREATE, name: 'showcase_proxy_map', type: 'proxy', target: 'https://example.invalid', outputMapping,
});
const unsupported = await mappedStep(proxied, callDataSpy().fn);
expect(unsupported?.status).toBe(501);
expect((unsupported!.body as { error: { code: string } }).error.code).toBe('NOT_IMPLEMENTED');
// 429: the endpoint budget, spent. Every one of these bodies is the
// error envelope, untouched by the declared projection.
const entries = new Map<string, unknown>();
const store: CounterStore = {
get: async <T,>(k: string) => entries.get(k) as T | undefined,
set: async (k: string, v: unknown) => { entries.set(k, v); },
};
const limited = ApiEndpointSchema.parse({
...CREATE, name: 'showcase_limited_map', outputMapping,
rateLimit: { enabled: true, windowMs: 1_000, maxRequests: 1 },
});
const policy = { limiters: createEndpointRateLimiterRegistry({ resolveCache: async () => store }) };
expect((await mappedStep(limited, callDataSpy().fn, undefined, policy))?.status).toBe(201);
const over = await mappedStep(limited, callDataSpy().fn, undefined, policy);
expect(over?.status).toBe(429);
for (const answer of [denied, bad, unsupported, over]) {
expect(JSON.stringify(answer?.body)).not.toContain('inquiry_id');
expect((answer!.body as { success: boolean }).success).toBe(false);
}
});
it('refuses a `transform` declaration at request time, without executing anything', async () => {
const spy = callDataSpy();
const withTransform = ApiEndpointSchema.parse({
...CREATE,
inputMapping: [{ source: 'price', target: 'amount', transform: 'convertToInt' }],
});
const answer = await mappedStep(withTransform, spy.fn);
expect(answer?.status).toBe(501);
const error = (answer!.body as { error: Record<string, unknown> }).error;
expect(error.code).toBe('NOT_IMPLEMENTED');
expect(String(error.message)).toContain('inputMapping[0].transform');
expect(spy.calls, 'a refused declaration still reached the pipeline').toEqual([]);
// No `Cache-Control` on a refusal, for the same reason as any error.
expect(answer?.headers).toBeUndefined();
});
it('refuses a broken outputMapping BEFORE the target runs, not after', async () => {
// The ordering that matters: a `create` with an unservable projection
// must not insert the record and then fail to answer with it.
const spy = callDataSpy();
const broken = ApiEndpointSchema.parse({
...CREATE,
outputMapping: [{ source: 'id', target: 'a' }, { source: 'name', target: 'a.b' }],
});
const answer = await mappedStep(broken, spy.fn);
expect(answer?.status).toBe(501);
expect(String((answer!.body as { error: { message: string } }).error.message))
.toContain('outputMapping[1].target');
expect(spy.calls, 'the record was created and then the answer was refused').toEqual([]);
});
});