@anvil-di/bellows 0.0.3 → 0.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/dist/authz.d.ts +28 -0
- package/dist/authz.d.ts.map +1 -0
- package/dist/authz.js +2 -0
- package/dist/authz.js.map +1 -0
- package/dist/decorators.d.ts +15 -0
- package/dist/decorators.d.ts.map +1 -1
- package/dist/decorators.js +17 -0
- package/dist/decorators.js.map +1 -1
- package/dist/errors.d.ts +95 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +143 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/routes.d.ts +68 -2
- package/dist/routes.d.ts.map +1 -1
- package/dist/routes.js +123 -7
- package/dist/routes.js.map +1 -1
- package/dist/schema.d.ts +75 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js.map +1 -1
- package/dist/sse.d.ts +46 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +92 -0
- package/dist/sse.js.map +1 -0
- package/package.json +3 -2
- package/src/authz.ts +32 -0
- package/src/decorators.ts +58 -0
- package/src/errors.test.ts +149 -0
- package/src/errors.ts +186 -0
- package/src/index.test.ts +733 -1
- package/src/index.ts +3 -0
- package/src/routes.ts +209 -7
- package/src/schema.ts +87 -1
- package/src/sse.test.ts +129 -0
- package/src/sse.ts +101 -0
package/src/index.test.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
+
import http from "node:http";
|
|
3
|
+
import type { AddressInfo } from "node:net";
|
|
4
|
+
import express from "express";
|
|
2
5
|
import { describe, expect, it } from "vitest";
|
|
3
6
|
import { z } from "zod";
|
|
4
|
-
import type { Validator } from "./schema.js";
|
|
7
|
+
import type { ResponseCodec, Validator } from "./schema.js";
|
|
5
8
|
import { withJsonSchema } from "./schema.js";
|
|
6
9
|
import {
|
|
7
10
|
Controller,
|
|
@@ -16,6 +19,9 @@ import {
|
|
|
16
19
|
Security,
|
|
17
20
|
Tag,
|
|
18
21
|
} from "./decorators.js";
|
|
22
|
+
import { bellowsRoutes, type RouteDefinition } from "./routes.js";
|
|
23
|
+
import { ForbiddenError, NotFoundError } from "./errors.js";
|
|
24
|
+
import type { AuthnService, AuthzService } from "./authz.js";
|
|
19
25
|
|
|
20
26
|
// --- Validator<T> structural compatibility ---
|
|
21
27
|
|
|
@@ -168,3 +174,729 @@ describe("bellowsCodegen", () => {
|
|
|
168
174
|
expect(hook.shouldRerun(["/other/dir/something.ts"])).toBe(false);
|
|
169
175
|
});
|
|
170
176
|
});
|
|
177
|
+
|
|
178
|
+
// --- bellowsRoutes: middleware chains + lifecycle hooks ---
|
|
179
|
+
|
|
180
|
+
/** Start an express app built from `routes`/`hooks` and return its base URL + a closer. */
|
|
181
|
+
async function serve(
|
|
182
|
+
routes: RouteDefinition[],
|
|
183
|
+
hooks?: Parameters<typeof bellowsRoutes>[1],
|
|
184
|
+
): Promise<{ url: string; close: () => Promise<void> }> {
|
|
185
|
+
const app = express();
|
|
186
|
+
app.use(bellowsRoutes(routes, hooks));
|
|
187
|
+
const server = http.createServer(app);
|
|
188
|
+
await new Promise<void>((resolve) => server.listen(0, resolve));
|
|
189
|
+
const { port } = server.address() as AddressInfo;
|
|
190
|
+
return {
|
|
191
|
+
url: `http://127.0.0.1:${port}`,
|
|
192
|
+
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
describe("bellowsRoutes", () => {
|
|
197
|
+
it("runs route middleware, in order, before the handler", async () => {
|
|
198
|
+
const calls: string[] = [];
|
|
199
|
+
const routes: RouteDefinition[] = [
|
|
200
|
+
{
|
|
201
|
+
method: "GET",
|
|
202
|
+
path: "/x",
|
|
203
|
+
middleware: [
|
|
204
|
+
(_req, _res, next) => { calls.push("first"); next(); },
|
|
205
|
+
(_req, _res, next) => { calls.push("second"); next(); },
|
|
206
|
+
],
|
|
207
|
+
handler: (_req, res) => { calls.push("handler"); res.json({ ok: true }); },
|
|
208
|
+
},
|
|
209
|
+
];
|
|
210
|
+
const { url, close } = await serve(routes);
|
|
211
|
+
try {
|
|
212
|
+
const res = await fetch(`${url}/x`);
|
|
213
|
+
expect(res.status).toBe(200);
|
|
214
|
+
expect(calls).toEqual(["first", "second", "handler"]);
|
|
215
|
+
} finally {
|
|
216
|
+
await close();
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it("short-circuits when middleware doesn't call next()", async () => {
|
|
221
|
+
let handlerCalled = false;
|
|
222
|
+
const routes: RouteDefinition[] = [
|
|
223
|
+
{
|
|
224
|
+
method: "GET",
|
|
225
|
+
path: "/x",
|
|
226
|
+
middleware: [(_req, res) => { res.status(401).json({ error: "unauthorized" }); }],
|
|
227
|
+
handler: (_req, res) => { handlerCalled = true; res.json({ ok: true }); },
|
|
228
|
+
},
|
|
229
|
+
];
|
|
230
|
+
const { url, close } = await serve(routes);
|
|
231
|
+
try {
|
|
232
|
+
const res = await fetch(`${url}/x`);
|
|
233
|
+
expect(res.status).toBe(401);
|
|
234
|
+
expect(handlerCalled).toBe(false);
|
|
235
|
+
} finally {
|
|
236
|
+
await close();
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
it("routes with no middleware still work", async () => {
|
|
241
|
+
const routes: RouteDefinition[] = [
|
|
242
|
+
{ method: "GET", path: "/x", handler: (_req, res) => res.json({ ok: true }) },
|
|
243
|
+
];
|
|
244
|
+
const { url, close } = await serve(routes);
|
|
245
|
+
try {
|
|
246
|
+
const res = await fetch(`${url}/x`);
|
|
247
|
+
expect(res.status).toBe(200);
|
|
248
|
+
} finally {
|
|
249
|
+
await close();
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
it("runs onRequest before every route's middleware and handler", async () => {
|
|
254
|
+
const calls: string[] = [];
|
|
255
|
+
const routes: RouteDefinition[] = [
|
|
256
|
+
{
|
|
257
|
+
method: "GET",
|
|
258
|
+
path: "/x",
|
|
259
|
+
middleware: [(_req, _res, next) => { calls.push("mw"); next(); }],
|
|
260
|
+
handler: (_req, res) => { calls.push("handler"); res.json({ ok: true }); },
|
|
261
|
+
},
|
|
262
|
+
];
|
|
263
|
+
const { url, close } = await serve(routes, {
|
|
264
|
+
onRequest: (_req, _res, next) => { calls.push("onRequest"); next(); },
|
|
265
|
+
});
|
|
266
|
+
try {
|
|
267
|
+
await fetch(`${url}/x`);
|
|
268
|
+
expect(calls).toEqual(["onRequest", "mw", "handler"]);
|
|
269
|
+
} finally {
|
|
270
|
+
await close();
|
|
271
|
+
}
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
it("runs onResponse after the response has been sent", async () => {
|
|
275
|
+
const calls: string[] = [];
|
|
276
|
+
const routes: RouteDefinition[] = [
|
|
277
|
+
{ method: "GET", path: "/x", handler: (_req, res) => { calls.push("handler"); res.json({ ok: true }); } },
|
|
278
|
+
];
|
|
279
|
+
const { url, close } = await serve(routes, {
|
|
280
|
+
onResponse: () => { calls.push("onResponse"); },
|
|
281
|
+
});
|
|
282
|
+
try {
|
|
283
|
+
await fetch(`${url}/x`);
|
|
284
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
285
|
+
expect(calls).toEqual(["handler", "onResponse"]);
|
|
286
|
+
} finally {
|
|
287
|
+
await close();
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
// --- bellowsRoutes: bodyParser (json/urlencoded/raw) + req.rawBody ---
|
|
293
|
+
|
|
294
|
+
describe("bellowsRoutes bodyParser", () => {
|
|
295
|
+
it("parses application/json bodies when bodyParser is \"json\"", async () => {
|
|
296
|
+
const routes: RouteDefinition[] = [
|
|
297
|
+
{
|
|
298
|
+
method: "POST",
|
|
299
|
+
path: "/x",
|
|
300
|
+
bodyParser: "json",
|
|
301
|
+
handler: (req, res) => res.json({ body: req.body, rawBody: req.rawBody?.toString() }),
|
|
302
|
+
},
|
|
303
|
+
];
|
|
304
|
+
const { url, close } = await serve(routes);
|
|
305
|
+
try {
|
|
306
|
+
const res = await fetch(`${url}/x`, {
|
|
307
|
+
method: "POST",
|
|
308
|
+
headers: { "content-type": "application/json" },
|
|
309
|
+
body: JSON.stringify({ name: "ada" }),
|
|
310
|
+
});
|
|
311
|
+
const json = await res.json();
|
|
312
|
+
expect(json.body).toEqual({ name: "ada" });
|
|
313
|
+
expect(json.rawBody).toBe(JSON.stringify({ name: "ada" }));
|
|
314
|
+
} finally {
|
|
315
|
+
await close();
|
|
316
|
+
}
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
it("parses application/x-www-form-urlencoded bodies when bodyParser is \"urlencoded\"", async () => {
|
|
320
|
+
const routes: RouteDefinition[] = [
|
|
321
|
+
{
|
|
322
|
+
method: "POST",
|
|
323
|
+
path: "/x",
|
|
324
|
+
bodyParser: "urlencoded",
|
|
325
|
+
handler: (req, res) => res.json({ body: req.body, rawBody: req.rawBody?.toString() }),
|
|
326
|
+
},
|
|
327
|
+
];
|
|
328
|
+
const { url, close } = await serve(routes);
|
|
329
|
+
try {
|
|
330
|
+
const res = await fetch(`${url}/x`, {
|
|
331
|
+
method: "POST",
|
|
332
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
333
|
+
body: "name=ada&role=admin",
|
|
334
|
+
});
|
|
335
|
+
const json = await res.json();
|
|
336
|
+
expect(json.body).toEqual({ name: "ada", role: "admin" });
|
|
337
|
+
expect(json.rawBody).toBe("name=ada&role=admin");
|
|
338
|
+
} finally {
|
|
339
|
+
await close();
|
|
340
|
+
}
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
it("captures raw bytes with no parsing when bodyParser is \"raw\"", async () => {
|
|
344
|
+
const routes: RouteDefinition[] = [
|
|
345
|
+
{
|
|
346
|
+
method: "POST",
|
|
347
|
+
path: "/x",
|
|
348
|
+
bodyParser: "raw",
|
|
349
|
+
handler: (req, res) => res.json({ rawBody: req.rawBody?.toString() }),
|
|
350
|
+
},
|
|
351
|
+
];
|
|
352
|
+
const { url, close } = await serve(routes);
|
|
353
|
+
try {
|
|
354
|
+
const res = await fetch(`${url}/x`, {
|
|
355
|
+
method: "POST",
|
|
356
|
+
headers: { "content-type": "application/octet-stream" },
|
|
357
|
+
body: "not-json-or-form",
|
|
358
|
+
});
|
|
359
|
+
const json = await res.json();
|
|
360
|
+
expect(json.rawBody).toBe("not-json-or-form");
|
|
361
|
+
} finally {
|
|
362
|
+
await close();
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
it("leaves req.body untouched when bodyParser is undeclared", async () => {
|
|
367
|
+
const routes: RouteDefinition[] = [
|
|
368
|
+
{ method: "POST", path: "/x", handler: (req, res) => res.json({ body: req.body ?? null }) },
|
|
369
|
+
];
|
|
370
|
+
const { url, close } = await serve(routes);
|
|
371
|
+
try {
|
|
372
|
+
const res = await fetch(`${url}/x`, {
|
|
373
|
+
method: "POST",
|
|
374
|
+
headers: { "content-type": "application/json" },
|
|
375
|
+
body: JSON.stringify({ name: "ada" }),
|
|
376
|
+
});
|
|
377
|
+
const json = await res.json();
|
|
378
|
+
expect(json.body).toBeNull();
|
|
379
|
+
} finally {
|
|
380
|
+
await close();
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
// --- bellowsRoutes: bodyParser's { kind: "codec", ... } form — the shape
|
|
386
|
+
// anvil-bellows codegen emits for the two-arg Body<S, C> param. Same
|
|
387
|
+
// relationship to the Rust codegen as the ResponseCodec/Produces block below:
|
|
388
|
+
// not testing codegen itself, just proving the emitted shape behaves
|
|
389
|
+
// correctly against a live server.
|
|
390
|
+
|
|
391
|
+
describe("bellowsRoutes bodyParser codec", () => {
|
|
392
|
+
const xmlCodec = {
|
|
393
|
+
contentType: "application/xml",
|
|
394
|
+
decode: (raw: Buffer) => ({ digits: /<Digits>(\d+)<\/Digits>/.exec(raw.toString())?.[1] }),
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
it("decodes a matching Content-Type through the codec before the handler runs", async () => {
|
|
398
|
+
const routes: RouteDefinition[] = [
|
|
399
|
+
{
|
|
400
|
+
method: "POST",
|
|
401
|
+
path: "/x",
|
|
402
|
+
bodyParser: { kind: "codec", contentType: xmlCodec.contentType, decode: xmlCodec.decode },
|
|
403
|
+
handler: (req, res) => res.json({ body: req.body, rawBody: req.rawBody?.toString() }),
|
|
404
|
+
},
|
|
405
|
+
];
|
|
406
|
+
const { url, close } = await serve(routes);
|
|
407
|
+
try {
|
|
408
|
+
const res = await fetch(`${url}/x`, {
|
|
409
|
+
method: "POST",
|
|
410
|
+
headers: { "content-type": "application/xml" },
|
|
411
|
+
body: "<Response><Digits>42</Digits></Response>",
|
|
412
|
+
});
|
|
413
|
+
const json = await res.json();
|
|
414
|
+
expect(json.body).toEqual({ digits: "42" });
|
|
415
|
+
expect(json.rawBody).toBe("<Response><Digits>42</Digits></Response>");
|
|
416
|
+
} finally {
|
|
417
|
+
await close();
|
|
418
|
+
}
|
|
419
|
+
});
|
|
420
|
+
|
|
421
|
+
it("leaves req.body untouched (unmatched Content-Type) without calling decode", async () => {
|
|
422
|
+
const routes: RouteDefinition[] = [
|
|
423
|
+
{
|
|
424
|
+
method: "POST",
|
|
425
|
+
path: "/x",
|
|
426
|
+
bodyParser: { kind: "codec", contentType: xmlCodec.contentType, decode: xmlCodec.decode },
|
|
427
|
+
handler: (req, res) => res.json({ body: req.body }),
|
|
428
|
+
},
|
|
429
|
+
];
|
|
430
|
+
const { url, close } = await serve(routes);
|
|
431
|
+
try {
|
|
432
|
+
const res = await fetch(`${url}/x`, {
|
|
433
|
+
method: "POST",
|
|
434
|
+
headers: { "content-type": "application/json" },
|
|
435
|
+
body: JSON.stringify({ name: "ada" }),
|
|
436
|
+
});
|
|
437
|
+
const json = await res.json();
|
|
438
|
+
expect(json.body).toBeUndefined();
|
|
439
|
+
} finally {
|
|
440
|
+
await close();
|
|
441
|
+
}
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
it("forwards a decode() error to the error handler as a 500", async () => {
|
|
445
|
+
const throwingCodec = {
|
|
446
|
+
contentType: "application/xml",
|
|
447
|
+
decode: (): never => {
|
|
448
|
+
throw new Error("malformed xml");
|
|
449
|
+
},
|
|
450
|
+
};
|
|
451
|
+
const routes: RouteDefinition[] = [
|
|
452
|
+
{
|
|
453
|
+
method: "POST",
|
|
454
|
+
path: "/x",
|
|
455
|
+
bodyParser: {
|
|
456
|
+
kind: "codec",
|
|
457
|
+
contentType: throwingCodec.contentType,
|
|
458
|
+
decode: throwingCodec.decode,
|
|
459
|
+
},
|
|
460
|
+
handler: (_req, res) => res.json({ ok: true }),
|
|
461
|
+
},
|
|
462
|
+
];
|
|
463
|
+
const { url, close } = await serve(routes);
|
|
464
|
+
try {
|
|
465
|
+
const res = await fetch(`${url}/x`, {
|
|
466
|
+
method: "POST",
|
|
467
|
+
headers: { "content-type": "application/xml" },
|
|
468
|
+
body: "<broken>",
|
|
469
|
+
});
|
|
470
|
+
expect(res.status).toBe(500);
|
|
471
|
+
} finally {
|
|
472
|
+
await close();
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
});
|
|
476
|
+
|
|
477
|
+
// --- ResponseCodec / Produces: the handler emitted for a `Produces<S, C>`
|
|
478
|
+
// route, run through a real Express server. This isn't testing anvil-bellows
|
|
479
|
+
// codegen itself (that's Rust-side, covered by its own unit tests) — it's
|
|
480
|
+
// proving that the *shape* of code codegen emits (schema.safeParse, then
|
|
481
|
+
// codec.contentType/encode instead of res.json) actually behaves correctly
|
|
482
|
+
// against a live server, not just as a string match.
|
|
483
|
+
|
|
484
|
+
describe("ResponseCodec / Produces (codegen output shape)", () => {
|
|
485
|
+
const TwimlResponseSchema = z.object({
|
|
486
|
+
type: z.literal("goodbye"),
|
|
487
|
+
text: z.string().min(1),
|
|
488
|
+
});
|
|
489
|
+
type TwimlResponse = z.infer<typeof TwimlResponseSchema>;
|
|
490
|
+
|
|
491
|
+
const twimlCodec: ResponseCodec<TwimlResponse> = {
|
|
492
|
+
contentType: "application/xml",
|
|
493
|
+
encode: (value) => `<Response><Say>${value.text}</Say></Response>`,
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
/** Exactly the handler body `anvil-bellows` codegen emits for `Produces<S, C>`. */
|
|
497
|
+
function producesHandler(getResult: () => unknown): RouteDefinition["handler"] {
|
|
498
|
+
return (_req, res) => {
|
|
499
|
+
const result = getResult();
|
|
500
|
+
const validated = TwimlResponseSchema.safeParse(result);
|
|
501
|
+
if (!validated.success) {
|
|
502
|
+
res.status(500).json(validated.error);
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
res.type(twimlCodec.contentType).send(twimlCodec.encode(validated.data));
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
it("sends the codec-encoded body with the codec's content-type, not JSON", async () => {
|
|
510
|
+
const routes: RouteDefinition[] = [
|
|
511
|
+
{
|
|
512
|
+
method: "POST",
|
|
513
|
+
path: "/webhooks/gather",
|
|
514
|
+
handler: producesHandler(() => ({ type: "goodbye", text: "bye now" })),
|
|
515
|
+
},
|
|
516
|
+
];
|
|
517
|
+
const { url, close } = await serve(routes);
|
|
518
|
+
try {
|
|
519
|
+
const res = await fetch(`${url}/webhooks/gather`, { method: "POST" });
|
|
520
|
+
expect(res.status).toBe(200);
|
|
521
|
+
expect(res.headers.get("content-type")).toMatch(/^application\/xml/);
|
|
522
|
+
const body = await res.text();
|
|
523
|
+
expect(body).toBe("<Response><Say>bye now</Say></Response>");
|
|
524
|
+
} finally {
|
|
525
|
+
await close();
|
|
526
|
+
}
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
it("still 500s with a JSON error body when the handler's return value fails schema validation", async () => {
|
|
530
|
+
const routes: RouteDefinition[] = [
|
|
531
|
+
{
|
|
532
|
+
method: "POST",
|
|
533
|
+
path: "/webhooks/gather",
|
|
534
|
+
// Missing `text` — fails TwimlResponseSchema before the codec ever runs.
|
|
535
|
+
handler: producesHandler(() => ({ type: "goodbye" })),
|
|
536
|
+
},
|
|
537
|
+
];
|
|
538
|
+
const { url, close } = await serve(routes);
|
|
539
|
+
try {
|
|
540
|
+
const res = await fetch(`${url}/webhooks/gather`, { method: "POST" });
|
|
541
|
+
expect(res.status).toBe(500);
|
|
542
|
+
expect(res.headers.get("content-type")).toMatch(/^application\/json/);
|
|
543
|
+
} finally {
|
|
544
|
+
await close();
|
|
545
|
+
}
|
|
546
|
+
});
|
|
547
|
+
});
|
|
548
|
+
|
|
549
|
+
// --- bellowsRoutes: error handling ---
|
|
550
|
+
|
|
551
|
+
describe("bellowsRoutes error handling", () => {
|
|
552
|
+
it("maps an HttpError thrown by a handler to its response", async () => {
|
|
553
|
+
const routes: RouteDefinition[] = [
|
|
554
|
+
{
|
|
555
|
+
method: "GET",
|
|
556
|
+
path: "/x",
|
|
557
|
+
handler: () => { throw new NotFoundError("no such thing"); },
|
|
558
|
+
},
|
|
559
|
+
];
|
|
560
|
+
const { url, close } = await serve(routes);
|
|
561
|
+
try {
|
|
562
|
+
const res = await fetch(`${url}/x`);
|
|
563
|
+
expect(res.status).toBe(404);
|
|
564
|
+
expect(await res.json()).toEqual({ error: "Not Found", message: "no such thing" });
|
|
565
|
+
} finally {
|
|
566
|
+
await close();
|
|
567
|
+
}
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
it("maps an HttpError rejected by an async handler to its response", async () => {
|
|
571
|
+
const routes: RouteDefinition[] = [
|
|
572
|
+
{
|
|
573
|
+
method: "GET",
|
|
574
|
+
path: "/x",
|
|
575
|
+
handler: async () => { throw new ForbiddenError(); },
|
|
576
|
+
},
|
|
577
|
+
];
|
|
578
|
+
const { url, close } = await serve(routes);
|
|
579
|
+
try {
|
|
580
|
+
const res = await fetch(`${url}/x`);
|
|
581
|
+
expect(res.status).toBe(403);
|
|
582
|
+
expect(await res.json()).toEqual({ error: "Forbidden" });
|
|
583
|
+
} finally {
|
|
584
|
+
await close();
|
|
585
|
+
}
|
|
586
|
+
});
|
|
587
|
+
|
|
588
|
+
it("falls back to a generic 500 for a non-HttpError", async () => {
|
|
589
|
+
const routes: RouteDefinition[] = [
|
|
590
|
+
{
|
|
591
|
+
method: "GET",
|
|
592
|
+
path: "/x",
|
|
593
|
+
handler: () => { throw new Error("some internal detail"); },
|
|
594
|
+
},
|
|
595
|
+
];
|
|
596
|
+
const { url, close } = await serve(routes);
|
|
597
|
+
try {
|
|
598
|
+
const res = await fetch(`${url}/x`);
|
|
599
|
+
expect(res.status).toBe(500);
|
|
600
|
+
expect(await res.json()).toEqual({
|
|
601
|
+
error: "Internal Server Error",
|
|
602
|
+
message: "Internal server error",
|
|
603
|
+
});
|
|
604
|
+
} finally {
|
|
605
|
+
await close();
|
|
606
|
+
}
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
it("uses a custom errorHandler when provided", async () => {
|
|
610
|
+
const routes: RouteDefinition[] = [
|
|
611
|
+
{
|
|
612
|
+
method: "GET",
|
|
613
|
+
path: "/x",
|
|
614
|
+
handler: () => { throw new NotFoundError(); },
|
|
615
|
+
},
|
|
616
|
+
];
|
|
617
|
+
const { url, close } = await serve(routes, {
|
|
618
|
+
errorHandler: (_err, _req, res, _next) => { res.status(418).json({ error: "teapot" }); },
|
|
619
|
+
});
|
|
620
|
+
try {
|
|
621
|
+
const res = await fetch(`${url}/x`);
|
|
622
|
+
expect(res.status).toBe(418);
|
|
623
|
+
expect(await res.json()).toEqual({ error: "teapot" });
|
|
624
|
+
} finally {
|
|
625
|
+
await close();
|
|
626
|
+
}
|
|
627
|
+
});
|
|
628
|
+
|
|
629
|
+
it("skips error handling entirely when errorHandler is false", async () => {
|
|
630
|
+
const routes: RouteDefinition[] = [
|
|
631
|
+
{
|
|
632
|
+
method: "GET",
|
|
633
|
+
path: "/x",
|
|
634
|
+
handler: () => { throw new NotFoundError(); },
|
|
635
|
+
},
|
|
636
|
+
];
|
|
637
|
+
const app = express();
|
|
638
|
+
app.use(bellowsRoutes(routes, { errorHandler: false }));
|
|
639
|
+
// Express's own default error handler takes over — still responds, but
|
|
640
|
+
// not with the shape `errorHandler` from ./errors.js would produce.
|
|
641
|
+
app.use(((err: unknown, _req, res, _next) => {
|
|
642
|
+
res.status(599).json({ fallback: true });
|
|
643
|
+
}) as express.ErrorRequestHandler);
|
|
644
|
+
|
|
645
|
+
const server = http.createServer(app);
|
|
646
|
+
await new Promise<void>((resolve) => server.listen(0, resolve));
|
|
647
|
+
const { port } = server.address() as AddressInfo;
|
|
648
|
+
try {
|
|
649
|
+
const res = await fetch(`http://127.0.0.1:${port}/x`);
|
|
650
|
+
expect(res.status).toBe(599);
|
|
651
|
+
expect(await res.json()).toEqual({ fallback: true });
|
|
652
|
+
} finally {
|
|
653
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
654
|
+
}
|
|
655
|
+
});
|
|
656
|
+
});
|
|
657
|
+
|
|
658
|
+
// --- bellowsRoutes: authn/authz cascade ---
|
|
659
|
+
|
|
660
|
+
describe("bellowsRoutes authn/authz", () => {
|
|
661
|
+
const identify =
|
|
662
|
+
(identified: boolean, user?: unknown): AuthnService["identify"] =>
|
|
663
|
+
() => (identified ? { identified: true, user } : { identified: false });
|
|
664
|
+
|
|
665
|
+
const authorize =
|
|
666
|
+
(decision: "allow" | "deny" | "next"): AuthzService["authorize"] =>
|
|
667
|
+
() => decision;
|
|
668
|
+
|
|
669
|
+
it("no authn/authz declared: request passes through unchanged", async () => {
|
|
670
|
+
const routes: RouteDefinition[] = [
|
|
671
|
+
{ method: "GET", path: "/x", handler: (_req, res) => res.json({ ok: true }) },
|
|
672
|
+
];
|
|
673
|
+
const { url, close } = await serve(routes);
|
|
674
|
+
try {
|
|
675
|
+
const res = await fetch(`${url}/x`);
|
|
676
|
+
expect(res.status).toBe(200);
|
|
677
|
+
} finally {
|
|
678
|
+
await close();
|
|
679
|
+
}
|
|
680
|
+
});
|
|
681
|
+
|
|
682
|
+
it("authn declared, none identify: 401, handler not called", async () => {
|
|
683
|
+
let handlerCalled = false;
|
|
684
|
+
const routes: RouteDefinition[] = [
|
|
685
|
+
{
|
|
686
|
+
method: "GET",
|
|
687
|
+
path: "/x",
|
|
688
|
+
authn: [{ identify: identify(false) }],
|
|
689
|
+
handler: (_req, res) => {
|
|
690
|
+
handlerCalled = true;
|
|
691
|
+
res.json({ ok: true });
|
|
692
|
+
},
|
|
693
|
+
},
|
|
694
|
+
];
|
|
695
|
+
const { url, close } = await serve(routes);
|
|
696
|
+
try {
|
|
697
|
+
const res = await fetch(`${url}/x`);
|
|
698
|
+
expect(res.status).toBe(401);
|
|
699
|
+
expect(handlerCalled).toBe(false);
|
|
700
|
+
} finally {
|
|
701
|
+
await close();
|
|
702
|
+
}
|
|
703
|
+
});
|
|
704
|
+
|
|
705
|
+
it("authn declared, first service identifies: handler runs, later services skipped", async () => {
|
|
706
|
+
const calls: string[] = [];
|
|
707
|
+
const routes: RouteDefinition[] = [
|
|
708
|
+
{
|
|
709
|
+
method: "GET",
|
|
710
|
+
path: "/x",
|
|
711
|
+
authn: [
|
|
712
|
+
{
|
|
713
|
+
identify: () => {
|
|
714
|
+
calls.push("first");
|
|
715
|
+
return { identified: true, user: { id: "u1" } };
|
|
716
|
+
},
|
|
717
|
+
},
|
|
718
|
+
{
|
|
719
|
+
identify: () => {
|
|
720
|
+
calls.push("second");
|
|
721
|
+
return { identified: true };
|
|
722
|
+
},
|
|
723
|
+
},
|
|
724
|
+
],
|
|
725
|
+
handler: (_req, res) => res.json({ ok: true }),
|
|
726
|
+
},
|
|
727
|
+
];
|
|
728
|
+
const { url, close } = await serve(routes);
|
|
729
|
+
try {
|
|
730
|
+
const res = await fetch(`${url}/x`);
|
|
731
|
+
expect(res.status).toBe(200);
|
|
732
|
+
expect(calls).toEqual(["first"]);
|
|
733
|
+
} finally {
|
|
734
|
+
await close();
|
|
735
|
+
}
|
|
736
|
+
});
|
|
737
|
+
|
|
738
|
+
it("authz declared, none allow: 403, handler not called", async () => {
|
|
739
|
+
let handlerCalled = false;
|
|
740
|
+
const routes: RouteDefinition[] = [
|
|
741
|
+
{
|
|
742
|
+
method: "GET",
|
|
743
|
+
path: "/x",
|
|
744
|
+
authz: [{ authorize: authorize("next") }],
|
|
745
|
+
handler: (_req, res) => {
|
|
746
|
+
handlerCalled = true;
|
|
747
|
+
res.json({ ok: true });
|
|
748
|
+
},
|
|
749
|
+
},
|
|
750
|
+
];
|
|
751
|
+
const { url, close } = await serve(routes);
|
|
752
|
+
try {
|
|
753
|
+
const res = await fetch(`${url}/x`);
|
|
754
|
+
expect(res.status).toBe(403);
|
|
755
|
+
expect(handlerCalled).toBe(false);
|
|
756
|
+
} finally {
|
|
757
|
+
await close();
|
|
758
|
+
}
|
|
759
|
+
});
|
|
760
|
+
|
|
761
|
+
it("authz declared, a service allows: handler runs", async () => {
|
|
762
|
+
const routes: RouteDefinition[] = [
|
|
763
|
+
{
|
|
764
|
+
method: "GET",
|
|
765
|
+
path: "/x",
|
|
766
|
+
authz: [{ authorize: authorize("next") }, { authorize: authorize("allow") }],
|
|
767
|
+
handler: (_req, res) => res.json({ ok: true }),
|
|
768
|
+
},
|
|
769
|
+
];
|
|
770
|
+
const { url, close } = await serve(routes);
|
|
771
|
+
try {
|
|
772
|
+
const res = await fetch(`${url}/x`);
|
|
773
|
+
expect(res.status).toBe(200);
|
|
774
|
+
} finally {
|
|
775
|
+
await close();
|
|
776
|
+
}
|
|
777
|
+
});
|
|
778
|
+
|
|
779
|
+
it("authz declared, a service denies: 403 without consulting later services", async () => {
|
|
780
|
+
const calls: string[] = [];
|
|
781
|
+
const routes: RouteDefinition[] = [
|
|
782
|
+
{
|
|
783
|
+
method: "GET",
|
|
784
|
+
path: "/x",
|
|
785
|
+
authz: [
|
|
786
|
+
{
|
|
787
|
+
authorize: () => {
|
|
788
|
+
calls.push("first");
|
|
789
|
+
return "deny";
|
|
790
|
+
},
|
|
791
|
+
},
|
|
792
|
+
{
|
|
793
|
+
authorize: () => {
|
|
794
|
+
calls.push("second");
|
|
795
|
+
return "allow";
|
|
796
|
+
},
|
|
797
|
+
},
|
|
798
|
+
],
|
|
799
|
+
handler: (_req, res) => res.json({ ok: true }),
|
|
800
|
+
},
|
|
801
|
+
];
|
|
802
|
+
const { url, close } = await serve(routes);
|
|
803
|
+
try {
|
|
804
|
+
const res = await fetch(`${url}/x`);
|
|
805
|
+
expect(res.status).toBe(403);
|
|
806
|
+
expect(calls).toEqual(["first"]);
|
|
807
|
+
} finally {
|
|
808
|
+
await close();
|
|
809
|
+
}
|
|
810
|
+
});
|
|
811
|
+
|
|
812
|
+
it("authn + authz both declared: authz only runs after authn succeeds, sees the identified user", async () => {
|
|
813
|
+
let seenUser: unknown;
|
|
814
|
+
const routes: RouteDefinition[] = [
|
|
815
|
+
{
|
|
816
|
+
method: "GET",
|
|
817
|
+
path: "/x",
|
|
818
|
+
authn: [{ identify: identify(true, { id: "u1" }) }],
|
|
819
|
+
authz: [
|
|
820
|
+
{
|
|
821
|
+
authorize: (_req, user) => {
|
|
822
|
+
seenUser = user;
|
|
823
|
+
return "allow";
|
|
824
|
+
},
|
|
825
|
+
},
|
|
826
|
+
],
|
|
827
|
+
handler: (_req, res) => res.json({ ok: true }),
|
|
828
|
+
},
|
|
829
|
+
];
|
|
830
|
+
const { url, close } = await serve(routes);
|
|
831
|
+
try {
|
|
832
|
+
const res = await fetch(`${url}/x`);
|
|
833
|
+
expect(res.status).toBe(200);
|
|
834
|
+
expect(seenUser).toEqual({ id: "u1" });
|
|
835
|
+
} finally {
|
|
836
|
+
await close();
|
|
837
|
+
}
|
|
838
|
+
});
|
|
839
|
+
|
|
840
|
+
it("authn + authz both declared, authn fails: authz never runs, 401", async () => {
|
|
841
|
+
let authzCalled = false;
|
|
842
|
+
const routes: RouteDefinition[] = [
|
|
843
|
+
{
|
|
844
|
+
method: "GET",
|
|
845
|
+
path: "/x",
|
|
846
|
+
authn: [{ identify: identify(false) }],
|
|
847
|
+
authz: [
|
|
848
|
+
{
|
|
849
|
+
authorize: () => {
|
|
850
|
+
authzCalled = true;
|
|
851
|
+
return "allow";
|
|
852
|
+
},
|
|
853
|
+
},
|
|
854
|
+
],
|
|
855
|
+
handler: (_req, res) => res.json({ ok: true }),
|
|
856
|
+
},
|
|
857
|
+
];
|
|
858
|
+
const { url, close } = await serve(routes);
|
|
859
|
+
try {
|
|
860
|
+
const res = await fetch(`${url}/x`);
|
|
861
|
+
expect(res.status).toBe(401);
|
|
862
|
+
expect(authzCalled).toBe(false);
|
|
863
|
+
} finally {
|
|
864
|
+
await close();
|
|
865
|
+
}
|
|
866
|
+
});
|
|
867
|
+
|
|
868
|
+
it("runs authn/authz before route middleware", async () => {
|
|
869
|
+
const calls: string[] = [];
|
|
870
|
+
const routes: RouteDefinition[] = [
|
|
871
|
+
{
|
|
872
|
+
method: "GET",
|
|
873
|
+
path: "/x",
|
|
874
|
+
authn: [
|
|
875
|
+
{
|
|
876
|
+
identify: () => {
|
|
877
|
+
calls.push("authn");
|
|
878
|
+
return { identified: true };
|
|
879
|
+
},
|
|
880
|
+
},
|
|
881
|
+
],
|
|
882
|
+
middleware: [
|
|
883
|
+
(_req, _res, next) => {
|
|
884
|
+
calls.push("middleware");
|
|
885
|
+
next();
|
|
886
|
+
},
|
|
887
|
+
],
|
|
888
|
+
handler: (_req, res) => {
|
|
889
|
+
calls.push("handler");
|
|
890
|
+
res.json({ ok: true });
|
|
891
|
+
},
|
|
892
|
+
},
|
|
893
|
+
];
|
|
894
|
+
const { url, close } = await serve(routes);
|
|
895
|
+
try {
|
|
896
|
+
await fetch(`${url}/x`);
|
|
897
|
+
expect(calls).toEqual(["authn", "middleware", "handler"]);
|
|
898
|
+
} finally {
|
|
899
|
+
await close();
|
|
900
|
+
}
|
|
901
|
+
});
|
|
902
|
+
});
|