@terreno/api 0.28.0 → 0.30.0
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/CHANGELOG.md +79 -0
- package/dist/actions.js +17 -8
- package/dist/actions.test.js +8 -3
- package/dist/api.arrayOperations.test.js +16 -8
- package/dist/api.coverage.test.js +2 -1
- package/dist/api.errorPaths.test.js +522 -1
- package/dist/api.errors.test.js +9 -0
- package/dist/api.js +137 -170
- package/dist/api.query.test.js +20 -8
- package/dist/api.test.js +12 -6
- package/dist/auth.coverage.test.d.ts +1 -0
- package/dist/auth.coverage.test.js +202 -0
- package/dist/auth.test.js +159 -0
- package/dist/docLoader.js +5 -1
- package/dist/envConfigurationPlugin.d.ts +1 -1
- package/dist/envConfigurationPlugin.js +0 -2
- package/dist/errors.d.ts +14 -0
- package/dist/errors.js +24 -2
- package/dist/errors.test.js +137 -0
- package/dist/httpClient.js +5 -1
- package/dist/plugins.d.ts +4 -4
- package/dist/plugins.js +51 -9
- package/dist/plugins.test.js +61 -17
- package/dist/realtime/registry.d.ts +3 -2
- package/package.json +2 -2
- package/src/actions.test.ts +8 -3
- package/src/actions.ts +19 -10
- package/src/api.arrayOperations.test.ts +16 -8
- package/src/api.coverage.test.ts +2 -1
- package/src/api.errorPaths.test.ts +313 -3
- package/src/api.errors.test.ts +12 -0
- package/src/api.query.test.ts +20 -8
- package/src/api.test.ts +12 -6
- package/src/api.ts +141 -161
- package/src/auth.coverage.test.ts +101 -0
- package/src/auth.test.ts +125 -2
- package/src/docLoader.ts +6 -2
- package/src/envConfigurationPlugin.ts +2 -6
- package/src/errors.test.ts +106 -1
- package/src/errors.ts +25 -1
- package/src/httpClient.ts +6 -2
- package/src/plugins.test.ts +45 -9
- package/src/plugins.ts +72 -35
- package/src/realtime/changeStreamWatcher.ts +8 -1
- package/src/realtime/registry.ts +3 -4
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import {beforeEach, describe, expect, it, setSystemTime} from "bun:test";
|
|
2
|
+
import type express from "express";
|
|
3
|
+
import jwt from "jsonwebtoken";
|
|
4
|
+
import supertest from "supertest";
|
|
5
|
+
|
|
6
|
+
import {addAuthRoutes, addMeRoutes, setupAuth, type User, type UserModel} from "./auth";
|
|
7
|
+
import {getBaseServer, setupTestData, UserModel as TestUserModel} from "./tests";
|
|
8
|
+
|
|
9
|
+
const testUserModel = TestUserModel as unknown as UserModel;
|
|
10
|
+
|
|
11
|
+
const signTokenForId = (id: string): string =>
|
|
12
|
+
jwt.sign({id}, process.env.TOKEN_SECRET as string, {issuer: process.env.TOKEN_ISSUER});
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Builds a stand-in UserModel that reuses the real passport strategy but lets each test
|
|
16
|
+
* control what `findById` resolves to.
|
|
17
|
+
*/
|
|
18
|
+
const createStubUserModel = (overrides: Partial<UserModel>): UserModel => {
|
|
19
|
+
return {
|
|
20
|
+
createStrategy: () => testUserModel.createStrategy(),
|
|
21
|
+
findById: async () => null,
|
|
22
|
+
...overrides,
|
|
23
|
+
} as unknown as UserModel;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
describe("setupAuth token extraction", () => {
|
|
27
|
+
beforeEach(async () => {
|
|
28
|
+
setSystemTime();
|
|
29
|
+
await setupTestData();
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("reads the token from the jwt cookie when no authorization header is present", async () => {
|
|
33
|
+
const app = getBaseServer();
|
|
34
|
+
const admin = await TestUserModel.findOne({email: "admin@example.com"});
|
|
35
|
+
const token = signTokenForId(String(admin?._id));
|
|
36
|
+
// Emulate cookie-parser, which consumers mount before setupAuth.
|
|
37
|
+
app.use((req: express.Request, _res: express.Response, next: express.NextFunction) => {
|
|
38
|
+
req.cookies = {jwt: token};
|
|
39
|
+
next();
|
|
40
|
+
});
|
|
41
|
+
setupAuth(app, testUserModel);
|
|
42
|
+
addMeRoutes(app, testUserModel);
|
|
43
|
+
|
|
44
|
+
const res = await supertest.agent(app).get("/auth/me").expect(200);
|
|
45
|
+
expect(res.body.data.email).toBe("admin@example.com");
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("logs the JWT setup message when not running in test mode", async () => {
|
|
49
|
+
const app = getBaseServer();
|
|
50
|
+
process.env.NODE_ENV = "development";
|
|
51
|
+
try {
|
|
52
|
+
setupAuth(app, testUserModel);
|
|
53
|
+
addAuthRoutes(app, testUserModel);
|
|
54
|
+
addMeRoutes(app, testUserModel);
|
|
55
|
+
const res = await supertest
|
|
56
|
+
.agent(app)
|
|
57
|
+
.post("/auth/login")
|
|
58
|
+
.send({email: "admin@example.com", password: "securePassword"})
|
|
59
|
+
.expect(200);
|
|
60
|
+
expect(res.body.data.token).toBeDefined();
|
|
61
|
+
} finally {
|
|
62
|
+
process.env.NODE_ENV = "test";
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
describe("addMeRoutes without a resolvable user", () => {
|
|
68
|
+
beforeEach(async () => {
|
|
69
|
+
setSystemTime();
|
|
70
|
+
await setupTestData();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("returns 401 when the authenticated user has no id", async () => {
|
|
74
|
+
const app = getBaseServer();
|
|
75
|
+
// The anonymous user has no id, so the /me handlers cannot look it up.
|
|
76
|
+
const anonymousModel = createStubUserModel({
|
|
77
|
+
createAnonymousUser: async () => ({}) as User,
|
|
78
|
+
});
|
|
79
|
+
setupAuth(app, anonymousModel);
|
|
80
|
+
addMeRoutes(app, anonymousModel);
|
|
81
|
+
const agent = supertest
|
|
82
|
+
.agent(app)
|
|
83
|
+
.set("authorization", `Bearer ${signTokenForId("507f1f77bcf86cd799439011")}`);
|
|
84
|
+
|
|
85
|
+
await agent.get("/auth/me").expect(401);
|
|
86
|
+
await agent.patch("/auth/me").send({name: "New Name"}).expect(401);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("returns 404 when the user cannot be found for the me routes", async () => {
|
|
90
|
+
const app = getBaseServer();
|
|
91
|
+
const admin = await TestUserModel.findOne({email: "admin@example.com"});
|
|
92
|
+
setupAuth(app, testUserModel);
|
|
93
|
+
addMeRoutes(app, createStubUserModel({}));
|
|
94
|
+
const agent = supertest
|
|
95
|
+
.agent(app)
|
|
96
|
+
.set("authorization", `Bearer ${signTokenForId(String(admin?._id))}`);
|
|
97
|
+
|
|
98
|
+
await agent.get("/auth/me").expect(404);
|
|
99
|
+
await agent.patch("/auth/me").send({name: "New Name"}).expect(404);
|
|
100
|
+
});
|
|
101
|
+
});
|
package/src/auth.test.ts
CHANGED
|
@@ -1,13 +1,21 @@
|
|
|
1
1
|
// noExplicitAny: test mock typing
|
|
2
2
|
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
3
|
import {afterEach, beforeEach, describe, expect, it, setSystemTime, spyOn} from "bun:test";
|
|
4
|
-
import
|
|
4
|
+
import express from "express";
|
|
5
5
|
import type jwt from "jsonwebtoken";
|
|
6
6
|
import supertest from "supertest";
|
|
7
7
|
import type TestAgent from "supertest/lib/agent";
|
|
8
8
|
|
|
9
9
|
import {modelRouter} from "./api";
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
type UserModel as AuthUserModel,
|
|
12
|
+
addAuthRoutes,
|
|
13
|
+
addMeRoutes,
|
|
14
|
+
generateTokens,
|
|
15
|
+
setupAuth,
|
|
16
|
+
signupUser,
|
|
17
|
+
} from "./auth";
|
|
18
|
+
import {logger} from "./logger";
|
|
11
19
|
import {Permissions} from "./permissions";
|
|
12
20
|
import {getCurrentRequestContext} from "./requestContext";
|
|
13
21
|
import {TerrenoApp} from "./terrenoApp";
|
|
@@ -1479,3 +1487,118 @@ describe("auth error paths when the user lookup fails", () => {
|
|
|
1479
1487
|
}
|
|
1480
1488
|
});
|
|
1481
1489
|
});
|
|
1490
|
+
|
|
1491
|
+
describe("cookie based JWT extraction", () => {
|
|
1492
|
+
afterEach(() => {
|
|
1493
|
+
setSystemTime();
|
|
1494
|
+
});
|
|
1495
|
+
|
|
1496
|
+
it("authenticates /auth/me from a jwt cookie", async () => {
|
|
1497
|
+
setSystemTime();
|
|
1498
|
+
const {users} = await setupTestData();
|
|
1499
|
+
const jwtLib = (await import("jsonwebtoken")).default;
|
|
1500
|
+
const token = jwtLib.sign({id: String(users.admin._id)}, process.env.TOKEN_SECRET as string, {
|
|
1501
|
+
issuer: process.env.TOKEN_ISSUER,
|
|
1502
|
+
});
|
|
1503
|
+
const app = getBaseServer();
|
|
1504
|
+
// Stand in for cookie-parser: the extractor prefers req.cookies.jwt over the auth header.
|
|
1505
|
+
app.use((req: express.Request, _res: express.Response, next: express.NextFunction) => {
|
|
1506
|
+
req.cookies = {jwt: token};
|
|
1507
|
+
next();
|
|
1508
|
+
});
|
|
1509
|
+
setupAuth(app, UserModel as unknown as AuthUserModel);
|
|
1510
|
+
addMeRoutes(app, UserModel as unknown as AuthUserModel);
|
|
1511
|
+
|
|
1512
|
+
const res = await supertest.agent(app).get("/auth/me").expect(200);
|
|
1513
|
+
expect(res.body.data.email).toBe("admin@example.com");
|
|
1514
|
+
});
|
|
1515
|
+
});
|
|
1516
|
+
|
|
1517
|
+
describe("auth logging outside of the test environment", () => {
|
|
1518
|
+
const originalNodeEnv = process.env.NODE_ENV;
|
|
1519
|
+
|
|
1520
|
+
afterEach(() => {
|
|
1521
|
+
setSystemTime();
|
|
1522
|
+
process.env.NODE_ENV = originalNodeEnv;
|
|
1523
|
+
});
|
|
1524
|
+
|
|
1525
|
+
it("logs JWT setup and successful logins when NODE_ENV is not test", async () => {
|
|
1526
|
+
setSystemTime();
|
|
1527
|
+
await setupTestData();
|
|
1528
|
+
process.env.NODE_ENV = "development";
|
|
1529
|
+
const debugSpy = spyOn(logger, "debug");
|
|
1530
|
+
const infoSpy = spyOn(logger, "info");
|
|
1531
|
+
try {
|
|
1532
|
+
const app = getBaseServer();
|
|
1533
|
+
setupAuth(app, UserModel as unknown as AuthUserModel);
|
|
1534
|
+
addAuthRoutes(app, UserModel as unknown as AuthUserModel);
|
|
1535
|
+
|
|
1536
|
+
const res = await supertest
|
|
1537
|
+
.agent(app)
|
|
1538
|
+
.post("/auth/login")
|
|
1539
|
+
.send({email: "notAdmin@example.com", password: "password"})
|
|
1540
|
+
.expect(200);
|
|
1541
|
+
expect(res.body.data.token).toBeDefined();
|
|
1542
|
+
expect(
|
|
1543
|
+
debugSpy.mock.calls.some(([message]) =>
|
|
1544
|
+
String(message).includes("Setting up JWT Authentication")
|
|
1545
|
+
)
|
|
1546
|
+
).toBe(true);
|
|
1547
|
+
expect(
|
|
1548
|
+
infoSpy.mock.calls.some(([message]) => String(message).includes("User logged in"))
|
|
1549
|
+
).toBe(true);
|
|
1550
|
+
} finally {
|
|
1551
|
+
debugSpy.mockRestore();
|
|
1552
|
+
infoSpy.mockRestore();
|
|
1553
|
+
}
|
|
1554
|
+
});
|
|
1555
|
+
});
|
|
1556
|
+
|
|
1557
|
+
describe("/me routes with an already populated req.user", () => {
|
|
1558
|
+
const buildApp = (
|
|
1559
|
+
user: {_id?: string; id?: string} | undefined,
|
|
1560
|
+
foundUser: unknown
|
|
1561
|
+
): express.Application => {
|
|
1562
|
+
const app = express();
|
|
1563
|
+
app.use(express.json());
|
|
1564
|
+
app.use((req: express.Request, _res: express.Response, next: express.NextFunction) => {
|
|
1565
|
+
req.user = user as unknown as express.Request["user"];
|
|
1566
|
+
next();
|
|
1567
|
+
});
|
|
1568
|
+
const stubUserModel = {
|
|
1569
|
+
findById: async () => foundUser,
|
|
1570
|
+
} as unknown as AuthUserModel;
|
|
1571
|
+
addMeRoutes(app, stubUserModel);
|
|
1572
|
+
return app;
|
|
1573
|
+
};
|
|
1574
|
+
|
|
1575
|
+
it("returns 401 from GET /auth/me when the request user has no id", async () => {
|
|
1576
|
+
await supertest
|
|
1577
|
+
.agent(buildApp({_id: "abc"}, null))
|
|
1578
|
+
.get("/auth/me")
|
|
1579
|
+
.expect(401);
|
|
1580
|
+
});
|
|
1581
|
+
|
|
1582
|
+
it("returns 401 from PATCH /auth/me when the request user has no id", async () => {
|
|
1583
|
+
await supertest
|
|
1584
|
+
.agent(buildApp({_id: "abc"}, null))
|
|
1585
|
+
.patch("/auth/me")
|
|
1586
|
+
.send({name: "Updated"})
|
|
1587
|
+
.expect(401);
|
|
1588
|
+
});
|
|
1589
|
+
|
|
1590
|
+
it("returns 404 from GET /auth/me when the user record no longer exists", async () => {
|
|
1591
|
+
await supertest
|
|
1592
|
+
.agent(buildApp({id: "abc"}, null))
|
|
1593
|
+
.get("/auth/me")
|
|
1594
|
+
.expect(404);
|
|
1595
|
+
});
|
|
1596
|
+
|
|
1597
|
+
it("returns 404 from PATCH /auth/me when the user record no longer exists", async () => {
|
|
1598
|
+
await supertest
|
|
1599
|
+
.agent(buildApp({id: "abc"}, null))
|
|
1600
|
+
.patch("/auth/me")
|
|
1601
|
+
.send({name: "Updated"})
|
|
1602
|
+
.expect(404);
|
|
1603
|
+
});
|
|
1604
|
+
});
|
package/src/docLoader.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import mongoose, {type Model} from "mongoose";
|
|
2
2
|
|
|
3
3
|
import {addPopulateToQuery} from "./api";
|
|
4
|
-
import {APIError, isAPIError, NotFoundError} from "./errors";
|
|
4
|
+
import {APIError, errorDetail, isAPIError, NotFoundError} from "./errors";
|
|
5
5
|
import type {PopulatePath} from "./populate";
|
|
6
6
|
|
|
7
7
|
/**
|
|
@@ -28,7 +28,8 @@ export const loadDocOr404 = async <T>(
|
|
|
28
28
|
throw new APIError({
|
|
29
29
|
cause: error,
|
|
30
30
|
code: "get-error",
|
|
31
|
-
detail: `GET failed on ${id}`,
|
|
31
|
+
detail: `GET failed on ${id}: ${errorDetail(error)}`,
|
|
32
|
+
meta: {model: model.modelName},
|
|
32
33
|
status: 500,
|
|
33
34
|
title: "GET error",
|
|
34
35
|
});
|
|
@@ -42,6 +43,7 @@ export const loadDocOr404 = async <T>(
|
|
|
42
43
|
|
|
43
44
|
if (!hiddenDoc) {
|
|
44
45
|
throw new NotFoundError({
|
|
46
|
+
code: "document-not-found",
|
|
45
47
|
detail: notFoundDetail,
|
|
46
48
|
title: "Document not found",
|
|
47
49
|
});
|
|
@@ -58,11 +60,13 @@ export const loadDocOr404 = async <T>(
|
|
|
58
60
|
|
|
59
61
|
if (!reason) {
|
|
60
62
|
throw new NotFoundError({
|
|
63
|
+
code: "document-not-found",
|
|
61
64
|
detail: notFoundDetail,
|
|
62
65
|
title: "Document not found",
|
|
63
66
|
});
|
|
64
67
|
}
|
|
65
68
|
throw new NotFoundError({
|
|
69
|
+
code: "document-not-found",
|
|
66
70
|
detail: notFoundDetail,
|
|
67
71
|
disableExternalErrorTracking: true,
|
|
68
72
|
meta: reason,
|
|
@@ -60,9 +60,7 @@ const mapToObject = (
|
|
|
60
60
|
|
|
61
61
|
const refreshFromDoc = async (Model: Model<unknown>): Promise<void> => {
|
|
62
62
|
try {
|
|
63
|
-
|
|
64
|
-
// biome-ignore lint/suspicious/noExplicitAny: doc shape determined by consumer schema
|
|
65
|
-
const doc = (await findOneOrNoneFor(Model as Model<any>, {})) as
|
|
63
|
+
const doc = (await findOneOrNoneFor(Model, {})) as
|
|
66
64
|
| (Document & {env?: Map<string, string> | Record<string, string>})
|
|
67
65
|
| null;
|
|
68
66
|
Config.setCachedEnv(mapToObject(doc?.env));
|
|
@@ -73,9 +71,7 @@ const refreshFromDoc = async (Model: Model<unknown>): Promise<void> => {
|
|
|
73
71
|
}
|
|
74
72
|
};
|
|
75
73
|
|
|
76
|
-
|
|
77
|
-
// biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
|
|
78
|
-
export const envConfigurationPlugin = (schema: Schema<any, any, any, any>): void => {
|
|
74
|
+
export const envConfigurationPlugin = (schema: Schema): void => {
|
|
79
75
|
schema.add({
|
|
80
76
|
env: {
|
|
81
77
|
default: () => new Map<string, string>(),
|
package/src/errors.test.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import {beforeEach, describe, expect, it, mock, spyOn} from "bun:test";
|
|
2
2
|
import * as Sentry from "@sentry/bun";
|
|
3
|
-
import type
|
|
3
|
+
import express, {type NextFunction, type Request, type Response} from "express";
|
|
4
4
|
import mongoose, {Schema} from "mongoose";
|
|
5
|
+
import supertest from "supertest";
|
|
5
6
|
|
|
6
7
|
import {
|
|
7
8
|
APIError,
|
|
@@ -9,6 +10,7 @@ import {
|
|
|
9
10
|
apiUnauthorizedMiddleware,
|
|
10
11
|
BadRequestError,
|
|
11
12
|
ConflictError,
|
|
13
|
+
errorDetail,
|
|
12
14
|
errorMessage,
|
|
13
15
|
errorStack,
|
|
14
16
|
errorsPlugin,
|
|
@@ -422,6 +424,109 @@ describe("apiUnauthorizedMiddleware", () => {
|
|
|
422
424
|
expect(next).toHaveBeenCalledWith(err);
|
|
423
425
|
expect(res.status).not.toHaveBeenCalled();
|
|
424
426
|
});
|
|
427
|
+
|
|
428
|
+
it("forwards an APIError titled Unauthorized so it keeps its own status", () => {
|
|
429
|
+
const err = new ForbiddenError({
|
|
430
|
+
code: "org-membership-required",
|
|
431
|
+
detail: "You are not a member of this organization",
|
|
432
|
+
title: "Unauthorized",
|
|
433
|
+
});
|
|
434
|
+
apiUnauthorizedMiddleware(
|
|
435
|
+
err,
|
|
436
|
+
req,
|
|
437
|
+
res as unknown as Response,
|
|
438
|
+
next as unknown as NextFunction
|
|
439
|
+
);
|
|
440
|
+
expect(next).toHaveBeenCalledWith(err);
|
|
441
|
+
expect(res.status).not.toHaveBeenCalled();
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
it("forwards a plain APIError titled Unauthorized rather than rewriting it to a 401", () => {
|
|
445
|
+
const err = new APIError({status: 403, title: "Unauthorized"});
|
|
446
|
+
apiUnauthorizedMiddleware(
|
|
447
|
+
err,
|
|
448
|
+
req,
|
|
449
|
+
res as unknown as Response,
|
|
450
|
+
next as unknown as NextFunction
|
|
451
|
+
);
|
|
452
|
+
expect(next).toHaveBeenCalledWith(err);
|
|
453
|
+
expect(res.status).not.toHaveBeenCalled();
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
it("forwards an Error subclass whose message is Unauthorized", () => {
|
|
457
|
+
class DomainUnauthorizedError extends Error {}
|
|
458
|
+
const err = new DomainUnauthorizedError("Unauthorized");
|
|
459
|
+
apiUnauthorizedMiddleware(
|
|
460
|
+
err,
|
|
461
|
+
req,
|
|
462
|
+
res as unknown as Response,
|
|
463
|
+
next as unknown as NextFunction
|
|
464
|
+
);
|
|
465
|
+
expect(next).toHaveBeenCalledWith(err);
|
|
466
|
+
expect(res.status).not.toHaveBeenCalled();
|
|
467
|
+
});
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
describe("apiUnauthorizedMiddleware in the terrenoApp middleware order", () => {
|
|
471
|
+
const buildApp = (): express.Express => {
|
|
472
|
+
const app = express();
|
|
473
|
+
app.get("/forbidden", (_req, _res, next) => {
|
|
474
|
+
next(
|
|
475
|
+
new ForbiddenError({
|
|
476
|
+
code: "org-membership-required",
|
|
477
|
+
detail: "You are not a member of this organization",
|
|
478
|
+
title: "Unauthorized",
|
|
479
|
+
})
|
|
480
|
+
);
|
|
481
|
+
});
|
|
482
|
+
app.get("/passport", (_req, _res, next) => {
|
|
483
|
+
next(new Error("Unauthorized"));
|
|
484
|
+
});
|
|
485
|
+
app.use(apiUnauthorizedMiddleware);
|
|
486
|
+
app.use(apiErrorMiddleware);
|
|
487
|
+
return app;
|
|
488
|
+
};
|
|
489
|
+
|
|
490
|
+
it("keeps a 403 titled Unauthorized a 403", async () => {
|
|
491
|
+
const res = await supertest(buildApp()).get("/forbidden").expect(403);
|
|
492
|
+
expect(res.body).toEqual({
|
|
493
|
+
code: "org-membership-required",
|
|
494
|
+
detail: "You are not a member of this organization",
|
|
495
|
+
status: 403,
|
|
496
|
+
title: "Unauthorized",
|
|
497
|
+
});
|
|
498
|
+
});
|
|
499
|
+
|
|
500
|
+
it("still converts a plain Passport Unauthorized error to a 401", async () => {
|
|
501
|
+
const res = await supertest(buildApp()).get("/passport").expect(401);
|
|
502
|
+
expect(res.body).toEqual({status: 401, title: "Unauthorized"});
|
|
503
|
+
});
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
describe("errorDetail", () => {
|
|
507
|
+
it("combines an APIError's title and detail", () => {
|
|
508
|
+
const error = new ConflictError({
|
|
509
|
+
code: "schedule-item-staff-conflict",
|
|
510
|
+
detail: "Conflict detected for Dr. Ada on 2026-07-31",
|
|
511
|
+
title: "Conflict detected",
|
|
512
|
+
});
|
|
513
|
+
expect(errorDetail(error)).toBe(
|
|
514
|
+
"Conflict detected: Conflict detected for Dr. Ada on 2026-07-31"
|
|
515
|
+
);
|
|
516
|
+
});
|
|
517
|
+
|
|
518
|
+
it("falls back to the title when an APIError has no detail", () => {
|
|
519
|
+
expect(errorDetail(new APIError({title: "Conflict detected"}))).toBe("Conflict detected");
|
|
520
|
+
});
|
|
521
|
+
|
|
522
|
+
it("returns the message for a plain Error", () => {
|
|
523
|
+
expect(errorDetail(new Error("boom"))).toBe("boom");
|
|
524
|
+
});
|
|
525
|
+
|
|
526
|
+
it("stringifies non-Error values", () => {
|
|
527
|
+
expect(errorDetail("boom")).toBe("boom");
|
|
528
|
+
expect(errorDetail(42)).toBe("42");
|
|
529
|
+
});
|
|
425
530
|
});
|
|
426
531
|
|
|
427
532
|
describe("apiErrorMiddleware", () => {
|
package/src/errors.ts
CHANGED
|
@@ -339,6 +339,18 @@ export const errorMessage = (error: unknown): string => {
|
|
|
339
339
|
return String(error);
|
|
340
340
|
};
|
|
341
341
|
|
|
342
|
+
/**
|
|
343
|
+
* Extract the fullest human-readable text from an unknown error, for use as the `detail` of a
|
|
344
|
+
* wrapper error. An `APIError`'s `message` is exactly its `title`, so `errorMessage` alone would
|
|
345
|
+
* drop the per-occurrence text the caller put in `detail`.
|
|
346
|
+
*/
|
|
347
|
+
export const errorDetail = (error: unknown): string => {
|
|
348
|
+
if (isAPIError(error) && error.detail) {
|
|
349
|
+
return `${error.title}: ${error.detail}`;
|
|
350
|
+
}
|
|
351
|
+
return errorMessage(error);
|
|
352
|
+
};
|
|
353
|
+
|
|
342
354
|
/** Extract a stack trace string from an unknown error. */
|
|
343
355
|
export const errorStack = (error: unknown): string => {
|
|
344
356
|
if (error instanceof Error && error.stack) {
|
|
@@ -406,13 +418,25 @@ export const getAPIErrorBody = (error: APIError): Record<string, unknown> => {
|
|
|
406
418
|
return serializeAPIError(error) as unknown as Record<string, unknown>;
|
|
407
419
|
};
|
|
408
420
|
|
|
421
|
+
/**
|
|
422
|
+
* Converts the bare `Error("Unauthorized")` that Passport throws into a quiet 401.
|
|
423
|
+
*
|
|
424
|
+
* Only the plain `Error` prototype is matched. An `APIError` carries its own status, code,
|
|
425
|
+
* detail, and meta, so one whose title happens to be "Unauthorized" falls through to
|
|
426
|
+
* `apiErrorMiddleware`. A domain-specific `Error` subclass with the same message also falls
|
|
427
|
+
* through so its own handler can respond.
|
|
428
|
+
*/
|
|
409
429
|
export const apiUnauthorizedMiddleware = (
|
|
410
430
|
err: Error,
|
|
411
431
|
_req: Request,
|
|
412
432
|
res: Response,
|
|
413
433
|
next: NextFunction
|
|
414
434
|
) => {
|
|
415
|
-
if (
|
|
435
|
+
if (
|
|
436
|
+
!isAPIError(err) &&
|
|
437
|
+
err.message === "Unauthorized" &&
|
|
438
|
+
Object.getPrototypeOf(err) === Error.prototype
|
|
439
|
+
) {
|
|
416
440
|
// not using the actual APIError class here because we don't want to log it as an error.
|
|
417
441
|
res.status(401).json({status: 401, title: "Unauthorized"}).send();
|
|
418
442
|
} else {
|
package/src/httpClient.ts
CHANGED
|
@@ -4,7 +4,7 @@ import axios, {
|
|
|
4
4
|
type InternalAxiosRequestConfig,
|
|
5
5
|
} from "axios";
|
|
6
6
|
|
|
7
|
-
import {APIError} from "./errors";
|
|
7
|
+
import {APIError, InternalServerError} from "./errors";
|
|
8
8
|
import {logger as defaultLogger} from "./logger";
|
|
9
9
|
|
|
10
10
|
// Internal per-request state tracked on the axios config across interceptor retries.
|
|
@@ -344,7 +344,11 @@ export const createAuthenticatedClient = (
|
|
|
344
344
|
);
|
|
345
345
|
const accessToken = response.data?.access_token;
|
|
346
346
|
if (typeof accessToken !== "string" || accessToken.length === 0) {
|
|
347
|
-
throw new
|
|
347
|
+
throw new InternalServerError({
|
|
348
|
+
code: "http-client-error",
|
|
349
|
+
detail: `${apiName} token response has no access_token`,
|
|
350
|
+
title: "[httpClient] token response has no access_token",
|
|
351
|
+
});
|
|
348
352
|
}
|
|
349
353
|
return accessToken;
|
|
350
354
|
};
|
package/src/plugins.test.ts
CHANGED
|
@@ -7,7 +7,7 @@ import supertest from "supertest";
|
|
|
7
7
|
import type TestAgent from "supertest/lib/agent";
|
|
8
8
|
import {modelRouter} from "./api";
|
|
9
9
|
import {addAuthRoutes, setupAuth} from "./auth";
|
|
10
|
-
import type
|
|
10
|
+
import {type APIErrorConstructor, InternalServerError, isAPIError, NotFoundError} from "./errors";
|
|
11
11
|
import {Permissions} from "./permissions";
|
|
12
12
|
import {
|
|
13
13
|
baseUserPlugin,
|
|
@@ -170,7 +170,7 @@ describe("findOneOrNone", () => {
|
|
|
170
170
|
|
|
171
171
|
it("throws error with two matches.", async () => {
|
|
172
172
|
const fn = () => StuffModel.findOneOrNone({ownerId: "123"});
|
|
173
|
-
await expect(fn()).rejects.toThrow(
|
|
173
|
+
await expect(fn()).rejects.toThrow(/^findOne query returned multiple documents$/);
|
|
174
174
|
});
|
|
175
175
|
|
|
176
176
|
it("throws custom error with two matches.", async () => {
|
|
@@ -184,7 +184,10 @@ describe("findOneOrNone", () => {
|
|
|
184
184
|
// Check if the error has title and status properties
|
|
185
185
|
expect(error.title).toBe("Oh no!");
|
|
186
186
|
expect(error.status).toBe(400);
|
|
187
|
-
expect(error.detail).toBe(
|
|
187
|
+
expect(error.detail).toBe(
|
|
188
|
+
'Stuff.findOne query returned multiple documents. query: {"ownerId":"123"}'
|
|
189
|
+
);
|
|
190
|
+
expect(error.code).toBe("find-one-multiple-documents");
|
|
188
191
|
}
|
|
189
192
|
});
|
|
190
193
|
});
|
|
@@ -231,7 +234,7 @@ describe("findOneOrNoneFor", () => {
|
|
|
231
234
|
|
|
232
235
|
it("throws when multiple documents match", async () => {
|
|
233
236
|
const fn = () => findOneOrNoneFor(StuffModel, {ownerId: "123"});
|
|
234
|
-
await expect(fn()).rejects.toThrow(
|
|
237
|
+
await expect(fn()).rejects.toThrow(/^findOne query returned multiple documents$/);
|
|
235
238
|
});
|
|
236
239
|
|
|
237
240
|
it("forwards errorArgs to the thrown APIError", async () => {
|
|
@@ -271,7 +274,7 @@ describe("findOneOrNoneFor", () => {
|
|
|
271
274
|
|
|
272
275
|
it("throws when multiple documents match", async () => {
|
|
273
276
|
const fn = () => findOneOrNoneFor(BareThingModel, {ownerId: "123"});
|
|
274
|
-
await expect(fn()).rejects.toThrow(
|
|
277
|
+
await expect(fn()).rejects.toThrow(/^findOne query returned multiple documents$/);
|
|
275
278
|
});
|
|
276
279
|
|
|
277
280
|
it("forwards errorArgs to the thrown APIError", async () => {
|
|
@@ -310,7 +313,25 @@ describe("findExactlyOne", () => {
|
|
|
310
313
|
|
|
311
314
|
it("throws error with no matches.", async () => {
|
|
312
315
|
const fn = () => StuffModel.findExactlyOne({name: "OtherStuff"});
|
|
313
|
-
await expect(fn()).rejects.toThrow(
|
|
316
|
+
await expect(fn()).rejects.toThrow(/^findExactlyOne query returned no documents$/);
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
it("throws a NotFoundError carrying the model name in detail and meta", async () => {
|
|
320
|
+
try {
|
|
321
|
+
await StuffModel.findExactlyOne({name: "OtherStuff"});
|
|
322
|
+
throw new Error("Expected promise to reject");
|
|
323
|
+
} catch (error: unknown) {
|
|
324
|
+
expect(error).toBeInstanceOf(NotFoundError);
|
|
325
|
+
if (!isAPIError(error)) {
|
|
326
|
+
throw error;
|
|
327
|
+
}
|
|
328
|
+
expect(error.status).toBe(404);
|
|
329
|
+
expect(error.code).toBe("find-exactly-one-no-documents");
|
|
330
|
+
expect(error.detail).toBe(
|
|
331
|
+
'Stuff.findExactlyOne query returned no documents. query: {"name":"OtherStuff"}'
|
|
332
|
+
);
|
|
333
|
+
expect(error.meta).toEqual({model: "Stuff"});
|
|
334
|
+
}
|
|
314
335
|
});
|
|
315
336
|
|
|
316
337
|
it("returns a single match", async () => {
|
|
@@ -320,7 +341,7 @@ describe("findExactlyOne", () => {
|
|
|
320
341
|
|
|
321
342
|
it("throws error with two matches.", async () => {
|
|
322
343
|
const fn = () => StuffModel.findExactlyOne({ownerId: "123"});
|
|
323
|
-
await expect(fn()).rejects.toThrow(
|
|
344
|
+
await expect(fn()).rejects.toThrow(/^findExactlyOne query returned multiple documents$/);
|
|
324
345
|
});
|
|
325
346
|
|
|
326
347
|
it("throws custom error with two matches.", async () => {
|
|
@@ -334,7 +355,10 @@ describe("findExactlyOne", () => {
|
|
|
334
355
|
// Check if the error has title and status properties
|
|
335
356
|
expect(error.title).toBe("Oh no!");
|
|
336
357
|
expect(error.status).toBe(400);
|
|
337
|
-
expect(error.detail).toBe(
|
|
358
|
+
expect(error.detail).toBe(
|
|
359
|
+
'Stuff.findExactlyOne query returned multiple documents. query: {"ownerId":"123"}'
|
|
360
|
+
);
|
|
361
|
+
expect(error.code).toBe("find-exactly-one-multiple-documents");
|
|
338
362
|
}
|
|
339
363
|
});
|
|
340
364
|
});
|
|
@@ -378,7 +402,19 @@ describe("upsertPlugin", () => {
|
|
|
378
402
|
]);
|
|
379
403
|
|
|
380
404
|
const fn = () => (StuffModel as any).upsert({ownerId: "123"}, {name: "Updated"});
|
|
381
|
-
await expect(fn()).rejects.toThrow(
|
|
405
|
+
await expect(fn()).rejects.toThrow(/^upsert find query returned multiple documents$/);
|
|
406
|
+
try {
|
|
407
|
+
await fn();
|
|
408
|
+
} catch (error: unknown) {
|
|
409
|
+
expect(error).toBeInstanceOf(InternalServerError);
|
|
410
|
+
if (!isAPIError(error)) {
|
|
411
|
+
throw error;
|
|
412
|
+
}
|
|
413
|
+
expect(error.code).toBe("upsert-multiple-documents");
|
|
414
|
+
expect(error.detail).toBe(
|
|
415
|
+
'Stuff.upsert find query returned multiple documents. query: {"ownerId":"123"}'
|
|
416
|
+
);
|
|
417
|
+
}
|
|
382
418
|
});
|
|
383
419
|
|
|
384
420
|
it("combines conditions and update data for new documents", async () => {
|