@terreno/api 56.0.0-beta.0 → 56.0.0-beta.2
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 +2 -122
- package/LICENSE +21 -202
- package/dist/api.d.ts +3 -2
- package/dist/auth.js +21 -25
- package/dist/betterAuthSetup.d.ts +15 -1
- package/dist/betterAuthSetup.js +4 -6
- package/dist/configurationPlugin.js +2 -2
- package/dist/expressServer.js +11 -5
- package/dist/githubAuth.js +1 -4
- package/dist/plugins.d.ts +7 -6
- package/dist/plugins.js +24 -8
- package/dist/realtime/realtimeApp.d.ts +1 -1
- package/dist/realtime/realtimeApp.js +16 -8
- package/dist/realtime/types.d.ts +14 -0
- package/dist/sync/executors.js +14 -14
- package/dist/sync/models.js +1 -1
- package/dist/sync/registry.js +1 -1
- package/dist/sync/syncSeqPlugin.js +25 -29
- package/dist/tests/models.d.ts +27 -11
- package/dist/tests/models.js +5 -3
- package/dist/tests/testHelper.d.ts +9 -3
- package/package.json +5 -6
- package/src/actions.test.ts +19 -12
- package/src/actions.ts +2 -2
- package/src/api.coverage.test.ts +7 -9
- package/src/api.errorPaths.test.ts +47 -1
- package/src/api.errors.test.ts +32 -23
- package/src/api.ts +22 -12
- package/src/auth.test.ts +251 -1
- package/src/auth.ts +25 -23
- package/src/betterAuthSetup.ts +7 -7
- package/src/configuration.test.ts +59 -38
- package/src/configurationPlugin.test.ts +72 -42
- package/src/configurationPlugin.ts +2 -2
- package/src/consentApp.test.ts +12 -12
- package/src/expressServer.ts +11 -5
- package/src/githubAuth.ts +1 -3
- package/src/middleware.test.ts +16 -0
- package/src/models/versionConfig.ts +1 -1
- package/src/openApiBuilder.test.ts +24 -9
- package/src/openApiValidator.test.ts +41 -0
- package/src/permissions.test.ts +35 -25
- package/src/plugins.test.ts +24 -0
- package/src/plugins.ts +29 -11
- package/src/populate.test.ts +25 -16
- package/src/realtime/realtime.test.ts +239 -0
- package/src/realtime/realtimeApp.ts +15 -8
- package/src/realtime/realtimeAppSetup.test.ts +159 -0
- package/src/realtime/types.ts +14 -0
- package/src/secretProvidersGcpClient.test.ts +66 -0
- package/src/sync/executors.ts +16 -14
- package/src/sync/models.ts +2 -1
- package/src/sync/registry.ts +1 -1
- package/src/sync/syncFrontier.test.ts +2 -2
- package/src/sync/syncSeqPlugin.ts +43 -51
- package/src/tests/models.ts +8 -6
package/src/api.coverage.test.ts
CHANGED
|
@@ -1,15 +1,13 @@
|
|
|
1
|
-
// noExplicitAny: test mock typing
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
1
|
import {beforeEach, describe, expect, it} from "bun:test";
|
|
4
2
|
import type express from "express";
|
|
5
|
-
import mongoose from "mongoose";
|
|
3
|
+
import mongoose, {type HydratedDocument} from "mongoose";
|
|
6
4
|
import supertest from "supertest";
|
|
7
5
|
import type TestAgent from "supertest/lib/agent";
|
|
8
6
|
|
|
9
7
|
import {modelRouter} from "./api";
|
|
10
|
-
import {addAuthRoutes, setupAuth} from "./auth";
|
|
8
|
+
import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "./auth";
|
|
11
9
|
import {Permissions} from "./permissions";
|
|
12
|
-
import {type Food, FoodModel, getBaseServer, setupDb, UserModel} from "./tests";
|
|
10
|
+
import {type Food, FoodModel, getBaseServer, setupDb, type User, UserModel} from "./tests";
|
|
13
11
|
|
|
14
12
|
// A model without the isDeleted plugin so deletes call doc.deleteOne(). The
|
|
15
13
|
// document delete hook throws to exercise the hard-delete error branch.
|
|
@@ -24,7 +22,7 @@ const ExplosiveModel = mongoose.model<{name: string}>("ExplosiveCoverage", explo
|
|
|
24
22
|
describe("modelRouter error path coverage", () => {
|
|
25
23
|
let server: TestAgent;
|
|
26
24
|
let app: express.Application;
|
|
27
|
-
let admin:
|
|
25
|
+
let admin: HydratedDocument<User>;
|
|
28
26
|
let apple: Food;
|
|
29
27
|
|
|
30
28
|
beforeEach(async () => {
|
|
@@ -44,8 +42,8 @@ describe("modelRouter error path coverage", () => {
|
|
|
44
42
|
});
|
|
45
43
|
|
|
46
44
|
app = getBaseServer();
|
|
47
|
-
setupAuth(app, UserModel as
|
|
48
|
-
addAuthRoutes(app, UserModel as
|
|
45
|
+
setupAuth(app, UserModel as unknown as AuthUserModel);
|
|
46
|
+
addAuthRoutes(app, UserModel as unknown as AuthUserModel);
|
|
49
47
|
});
|
|
50
48
|
|
|
51
49
|
it("returns 400 when an array operation transformer throws a non-APIError", async () => {
|
|
@@ -104,7 +102,7 @@ describe("modelRouter error path coverage", () => {
|
|
|
104
102
|
const doc = await ExplosiveModel.create({name: "boom"});
|
|
105
103
|
app.use(
|
|
106
104
|
"/explosive",
|
|
107
|
-
modelRouter(ExplosiveModel
|
|
105
|
+
modelRouter(ExplosiveModel, {
|
|
108
106
|
allowAnonymous: true,
|
|
109
107
|
permissions: {
|
|
110
108
|
create: [Permissions.IsAny],
|
|
@@ -2,11 +2,12 @@ import {afterEach, beforeEach, describe, it, spyOn} from "bun:test";
|
|
|
2
2
|
import * as Sentry from "@sentry/bun";
|
|
3
3
|
import {assert} from "chai";
|
|
4
4
|
import type express from "express";
|
|
5
|
+
import {DateTime} from "luxon";
|
|
5
6
|
import mongoose from "mongoose";
|
|
6
7
|
import supertest from "supertest";
|
|
7
8
|
import type TestAgent from "supertest/lib/agent";
|
|
8
9
|
|
|
9
|
-
import {type ModelRouterOptions, modelRouter} from "./api";
|
|
10
|
+
import {type JSONValue, type ModelRouterOptions, modelRouter} from "./api";
|
|
10
11
|
import {addAuthRoutes, setupAuth} from "./auth";
|
|
11
12
|
import {ConflictError} from "./errors";
|
|
12
13
|
import {Permissions} from "./permissions";
|
|
@@ -192,6 +193,51 @@ describe("modelRouter error paths", () => {
|
|
|
192
193
|
saveSpy.mockRestore();
|
|
193
194
|
}
|
|
194
195
|
});
|
|
196
|
+
|
|
197
|
+
it("wraps failures while assembling the list response", async () => {
|
|
198
|
+
mountFood({
|
|
199
|
+
responseHandler: async (data) => {
|
|
200
|
+
const serialized = [...(data as Food[])] as Food[] & {slice: () => never};
|
|
201
|
+
serialized.slice = () => {
|
|
202
|
+
throw new Error("slice exploded");
|
|
203
|
+
};
|
|
204
|
+
return serialized as unknown as JSONValue;
|
|
205
|
+
},
|
|
206
|
+
});
|
|
207
|
+
const ownerId = new mongoose.Types.ObjectId();
|
|
208
|
+
await FoodModel.create([
|
|
209
|
+
{calories: 1, name: "First", ownerId},
|
|
210
|
+
{calories: 2, name: "Second", ownerId},
|
|
211
|
+
] as Partial<Food>[]);
|
|
212
|
+
|
|
213
|
+
// limit=1 fetches an extra doc, so the handler slices off the overflow.
|
|
214
|
+
const res = await server.get("/food?limit=1");
|
|
215
|
+
assert.equal(res.body.title, "Serialization error");
|
|
216
|
+
assert.include(res.body.detail, "slice exploded");
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it("rejects a patch when the stored timestamp cannot be parsed", async () => {
|
|
220
|
+
// `updated` is a string here so the router has to parse it as an ISO date.
|
|
221
|
+
const timestampSchema = new mongoose.Schema({
|
|
222
|
+
name: {description: "The name", type: String},
|
|
223
|
+
updated: {description: "Last update, as an ISO string", type: String},
|
|
224
|
+
});
|
|
225
|
+
const TimestampModel = mongoose.model(`StringTimestamp_${Date.now()}`, timestampSchema);
|
|
226
|
+
app.use(
|
|
227
|
+
"/timestamped",
|
|
228
|
+
modelRouter(TimestampModel, {allowAnonymous: true, permissions: anyPermissions})
|
|
229
|
+
);
|
|
230
|
+
server = supertest(app);
|
|
231
|
+
|
|
232
|
+
const doc = await TimestampModel.create({name: "Timeless", updated: "not-a-date"});
|
|
233
|
+
|
|
234
|
+
const res = await server
|
|
235
|
+
.patch(`/timestamped/${doc._id}`)
|
|
236
|
+
.set("If-Unmodified-Since", DateTime.now().toHTTP() as string)
|
|
237
|
+
.send({name: "Renamed"})
|
|
238
|
+
.expect(400);
|
|
239
|
+
assert.equal(res.body.title, "Invalid server timestamp");
|
|
240
|
+
});
|
|
195
241
|
});
|
|
196
242
|
|
|
197
243
|
interface Guarded {
|
package/src/api.errors.test.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
// noExplicitAny: test mock typing
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
1
|
import {describe, expect, it} from "bun:test";
|
|
4
|
-
import type {NextFunction} from "express";
|
|
2
|
+
import type {NextFunction, Request, Response} from "express";
|
|
5
3
|
import mongoose from "mongoose";
|
|
6
4
|
|
|
7
5
|
import {
|
|
@@ -122,47 +120,58 @@ describe("errors module", () => {
|
|
|
122
120
|
});
|
|
123
121
|
|
|
124
122
|
describe("apiUnauthorizedMiddleware", () => {
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
123
|
+
interface MockResponse {
|
|
124
|
+
body?: {status: number; title: string};
|
|
125
|
+
statusCode?: number;
|
|
126
|
+
json: (data: {status: number; title: string}) => MockResponse;
|
|
127
|
+
send: () => MockResponse;
|
|
128
|
+
status: (code: number) => MockResponse;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const createMockResponse = (): MockResponse => {
|
|
132
|
+
const res: MockResponse = {
|
|
133
|
+
json: (data) => {
|
|
134
|
+
res.body = data;
|
|
135
|
+
return res;
|
|
134
136
|
},
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
137
|
+
send: () => res,
|
|
138
|
+
status: (code) => {
|
|
139
|
+
res.statusCode = code;
|
|
140
|
+
return res;
|
|
138
141
|
},
|
|
139
142
|
};
|
|
140
|
-
|
|
143
|
+
return res;
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
it("returns 401 for Unauthorized errors", () => {
|
|
147
|
+
const err = new Error("Unauthorized");
|
|
148
|
+
const res = createMockResponse();
|
|
149
|
+
const next: NextFunction = () => {};
|
|
141
150
|
|
|
142
|
-
apiUnauthorizedMiddleware(err, {} as
|
|
143
|
-
expect(
|
|
144
|
-
expect(
|
|
151
|
+
apiUnauthorizedMiddleware(err, {} as Request, res as unknown as Response, next);
|
|
152
|
+
expect(res.statusCode).toBe(401);
|
|
153
|
+
expect(res.body?.title).toBe("Unauthorized");
|
|
145
154
|
});
|
|
146
155
|
|
|
147
156
|
it("calls next for non-Unauthorized errors", () => {
|
|
148
157
|
const err = new Error("Some other error");
|
|
149
158
|
let nextCalled = false;
|
|
150
|
-
const next = () => {
|
|
159
|
+
const next: NextFunction = () => {
|
|
151
160
|
nextCalled = true;
|
|
152
161
|
};
|
|
153
162
|
|
|
154
|
-
apiUnauthorizedMiddleware(err, {} as
|
|
163
|
+
apiUnauthorizedMiddleware(err, {} as Request, {} as Response, next);
|
|
155
164
|
expect(nextCalled).toBe(true);
|
|
156
165
|
});
|
|
157
166
|
|
|
158
167
|
it("calls next for an APIError whose title is Unauthorized", () => {
|
|
159
168
|
const err = new APIError({code: "not-a-member", status: 403, title: "Unauthorized"});
|
|
160
169
|
let nextArg: unknown;
|
|
161
|
-
const next = (error
|
|
170
|
+
const next: NextFunction = (error) => {
|
|
162
171
|
nextArg = error;
|
|
163
172
|
};
|
|
164
173
|
|
|
165
|
-
apiUnauthorizedMiddleware(err, {} as
|
|
174
|
+
apiUnauthorizedMiddleware(err, {} as Request, {} as Response, next);
|
|
166
175
|
expect(nextArg).toBe(err);
|
|
167
176
|
});
|
|
168
177
|
});
|
package/src/api.ts
CHANGED
|
@@ -22,7 +22,6 @@ import {
|
|
|
22
22
|
BadRequestError,
|
|
23
23
|
errorDetail,
|
|
24
24
|
ForbiddenError,
|
|
25
|
-
isAPIError,
|
|
26
25
|
NotFoundError,
|
|
27
26
|
passthroughOrWrap,
|
|
28
27
|
passthroughOrWrapWrite,
|
|
@@ -62,6 +61,10 @@ import {
|
|
|
62
61
|
} from "./transformers";
|
|
63
62
|
import {isValidObjectId} from "./utils";
|
|
64
63
|
|
|
64
|
+
// noExplicitAny: Framework routers accept consumer models with arbitrary query helpers, methods, virtuals, and hydrated document types
|
|
65
|
+
// biome-ignore lint/suspicious/noExplicitAny: Framework routers accept consumer models with arbitrary query helpers, methods, virtuals, and hydrated document types
|
|
66
|
+
type ModelLike<T> = Model<T, any, any, any, any, any>;
|
|
67
|
+
|
|
65
68
|
export type JSONPrimitive = string | number | boolean | null;
|
|
66
69
|
export interface JSONArray extends Array<JSONValue> {}
|
|
67
70
|
export interface JSONObject {
|
|
@@ -387,7 +390,7 @@ const parseDateRangeBound = (rawValue: unknown, queryKey: string): Date => {
|
|
|
387
390
|
* so admin changelist date-range filters map to valid Mongoose range queries.
|
|
388
391
|
*/
|
|
389
392
|
const mergeDateRangeQueryParams = <T>(
|
|
390
|
-
model:
|
|
393
|
+
model: ModelLike<T>,
|
|
391
394
|
query: Record<string, unknown>
|
|
392
395
|
): Record<string, unknown> => {
|
|
393
396
|
const schema = model.schema;
|
|
@@ -510,7 +513,7 @@ const shouldValidate = <T>(
|
|
|
510
513
|
|
|
511
514
|
// Get body validation middleware if validation is enabled
|
|
512
515
|
const getBodyValidationMiddleware = <T>(
|
|
513
|
-
model:
|
|
516
|
+
model: ModelLike<T>,
|
|
514
517
|
options: ModelRouterOptions<T>,
|
|
515
518
|
operation: "create" | "update"
|
|
516
519
|
): ((req: Request, res: Response, next: NextFunction) => void) => {
|
|
@@ -540,7 +543,7 @@ const getBodyValidationMiddleware = <T>(
|
|
|
540
543
|
|
|
541
544
|
// Get query validation middleware if validation is enabled
|
|
542
545
|
const getQueryValidationMiddleware = <T>(
|
|
543
|
-
model:
|
|
546
|
+
model: ModelLike<T>,
|
|
544
547
|
options: ModelRouterOptions<T>
|
|
545
548
|
): ((req: Request, res: Response, next: NextFunction) => void) => {
|
|
546
549
|
const querySchema = buildQuerySchemaFromFields(model, options.queryFields);
|
|
@@ -591,22 +594,22 @@ export interface ModelRouterRegistration {
|
|
|
591
594
|
*/
|
|
592
595
|
export function modelRouter<T>(
|
|
593
596
|
path: string,
|
|
594
|
-
model:
|
|
597
|
+
model: ModelLike<T>,
|
|
595
598
|
options: ModelRouterOptions<T>
|
|
596
599
|
): ModelRouterRegistration;
|
|
597
|
-
export function modelRouter<T>(model:
|
|
600
|
+
export function modelRouter<T>(model: ModelLike<T>, options: ModelRouterOptions<T>): express.Router;
|
|
598
601
|
export function modelRouter<T>(
|
|
599
|
-
pathOrModel: string |
|
|
600
|
-
modelOrOptions:
|
|
602
|
+
pathOrModel: string | ModelLike<T>,
|
|
603
|
+
modelOrOptions: ModelLike<T> | ModelRouterOptions<T>,
|
|
601
604
|
maybeOptions?: ModelRouterOptions<T>
|
|
602
605
|
): express.Router | ModelRouterRegistration {
|
|
603
|
-
let model:
|
|
606
|
+
let model: ModelLike<T>;
|
|
604
607
|
let options: ModelRouterOptions<T>;
|
|
605
608
|
let path: string | undefined;
|
|
606
609
|
|
|
607
610
|
if (typeof pathOrModel === "string") {
|
|
608
611
|
path = pathOrModel;
|
|
609
|
-
model = modelOrOptions as
|
|
612
|
+
model = modelOrOptions as ModelLike<T>;
|
|
610
613
|
options = maybeOptions as ModelRouterOptions<T>;
|
|
611
614
|
} else {
|
|
612
615
|
model = pathOrModel;
|
|
@@ -655,7 +658,10 @@ export function modelRouter<T>(
|
|
|
655
658
|
return router;
|
|
656
659
|
}
|
|
657
660
|
|
|
658
|
-
const _buildModelRouter = <T>(
|
|
661
|
+
const _buildModelRouter = <T>(
|
|
662
|
+
model: ModelLike<T>,
|
|
663
|
+
options: ModelRouterOptions<T>
|
|
664
|
+
): express.Router => {
|
|
659
665
|
const router = express.Router();
|
|
660
666
|
|
|
661
667
|
assertNoActionCollisions(model, options);
|
|
@@ -1181,7 +1187,11 @@ const _buildModelRouter = <T>(model: Model<T>, options: ModelRouterOptions<T>):
|
|
|
1181
1187
|
return arrayOperation(req, res, "DELETE");
|
|
1182
1188
|
};
|
|
1183
1189
|
// Set up routes for managing array fields. Check if there any array fields to add this for.
|
|
1184
|
-
if (
|
|
1190
|
+
if (
|
|
1191
|
+
(Object.values(model.schema.paths) as mongoose.SchemaType[]).find(
|
|
1192
|
+
(config) => config.instance === "Array"
|
|
1193
|
+
)
|
|
1194
|
+
) {
|
|
1185
1195
|
router.post(
|
|
1186
1196
|
"/:id/:field",
|
|
1187
1197
|
authenticateMiddleware(options.allowAnonymous),
|
package/src/auth.test.ts
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
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 {assert} from "chai";
|
|
5
|
+
import express from "express";
|
|
5
6
|
import type jwt from "jsonwebtoken";
|
|
6
7
|
import supertest from "supertest";
|
|
7
8
|
import type TestAgent from "supertest/lib/agent";
|
|
8
9
|
|
|
9
10
|
import {modelRouter} from "./api";
|
|
10
11
|
import {
|
|
12
|
+
type UserModel as AuthUserModel,
|
|
11
13
|
addAuthRoutes,
|
|
12
14
|
addMeRoutes,
|
|
13
15
|
generateTokens,
|
|
@@ -15,6 +17,7 @@ import {
|
|
|
15
17
|
MAX_PASSWORD_LENGTH,
|
|
16
18
|
setPasswordForUser,
|
|
17
19
|
setupAuth,
|
|
20
|
+
signupUser,
|
|
18
21
|
} from "./auth";
|
|
19
22
|
import {logger} from "./logger";
|
|
20
23
|
import {Permissions} from "./permissions";
|
|
@@ -811,6 +814,38 @@ describe("generateTokens edge cases", () => {
|
|
|
811
814
|
expect(result.token).toBeDefined();
|
|
812
815
|
expect(result.refreshToken).toBeUndefined();
|
|
813
816
|
});
|
|
817
|
+
|
|
818
|
+
it("falls back to the default expiration when TOKEN_EXPIRES_IN is invalid", async () => {
|
|
819
|
+
process.env.TOKEN_EXPIRES_IN = "not-a-duration";
|
|
820
|
+
const errorSpy = spyOn(logger, "error").mockImplementation(() => logger);
|
|
821
|
+
try {
|
|
822
|
+
const result = await generateTokens({_id: "user-123"});
|
|
823
|
+
const decoded = decodeTokenPayload<{exp: number}>(result.token as string);
|
|
824
|
+
// Falls back to the 15 minute default rather than failing token generation.
|
|
825
|
+
const expectedExp = Math.floor(Date.now() / 1000) + 15 * 60;
|
|
826
|
+
assert.isAbove(decoded.exp, expectedExp - 10);
|
|
827
|
+
assert.isBelow(decoded.exp, expectedExp + 10);
|
|
828
|
+
assert.include(String(errorSpy.mock.calls[0]?.[0]), "TOKEN_EXPIRES_IN");
|
|
829
|
+
} finally {
|
|
830
|
+
errorSpy.mockRestore();
|
|
831
|
+
}
|
|
832
|
+
});
|
|
833
|
+
|
|
834
|
+
it("falls back to the default expiration when REFRESH_TOKEN_EXPIRES_IN is invalid", async () => {
|
|
835
|
+
process.env.REFRESH_TOKEN_EXPIRES_IN = "not-a-duration";
|
|
836
|
+
const errorSpy = spyOn(logger, "error").mockImplementation(() => logger);
|
|
837
|
+
try {
|
|
838
|
+
const result = await generateTokens({_id: "user-123"});
|
|
839
|
+
const decoded = decodeTokenPayload<{exp: number}>(result.refreshToken as string);
|
|
840
|
+
// Falls back to the 30 day default rather than failing token generation.
|
|
841
|
+
const expectedExp = Math.floor(Date.now() / 1000) + 30 * 24 * 3600;
|
|
842
|
+
assert.isAbove(decoded.exp, expectedExp - 10);
|
|
843
|
+
assert.isBelow(decoded.exp, expectedExp + 10);
|
|
844
|
+
assert.include(String(errorSpy.mock.calls[0]?.[0]), "REFRESH_TOKEN_EXPIRES_IN");
|
|
845
|
+
} finally {
|
|
846
|
+
errorSpy.mockRestore();
|
|
847
|
+
}
|
|
848
|
+
});
|
|
814
849
|
});
|
|
815
850
|
|
|
816
851
|
describe("addAuthRoutes /refresh_token error paths", () => {
|
|
@@ -1554,3 +1589,218 @@ describe("setPasswordForUser", () => {
|
|
|
1554
1589
|
infoSpy.mockRestore();
|
|
1555
1590
|
});
|
|
1556
1591
|
});
|
|
1592
|
+
|
|
1593
|
+
describe("signupUser postCreate failures", () => {
|
|
1594
|
+
it("wraps and rethrows errors thrown by user.postCreate", async () => {
|
|
1595
|
+
let saveCalled = false;
|
|
1596
|
+
const failingUser = {
|
|
1597
|
+
postCreate: async () => {
|
|
1598
|
+
throw new Error("postCreate failed");
|
|
1599
|
+
},
|
|
1600
|
+
save: async () => {
|
|
1601
|
+
saveCalled = true;
|
|
1602
|
+
},
|
|
1603
|
+
};
|
|
1604
|
+
const fakeModel = {
|
|
1605
|
+
register: async () => failingUser,
|
|
1606
|
+
} as unknown as Parameters<typeof signupUser>[0];
|
|
1607
|
+
|
|
1608
|
+
await expect(signupUser(fakeModel, "new@example.com", "password123")).rejects.toThrow(
|
|
1609
|
+
"postCreate failed"
|
|
1610
|
+
);
|
|
1611
|
+
expect(saveCalled).toBe(false);
|
|
1612
|
+
});
|
|
1613
|
+
});
|
|
1614
|
+
|
|
1615
|
+
describe("auth error paths when the user lookup fails", () => {
|
|
1616
|
+
let app: express.Application;
|
|
1617
|
+
let agent: TestAgent;
|
|
1618
|
+
let admin: {_id: {toString: () => string}};
|
|
1619
|
+
|
|
1620
|
+
beforeEach(async () => {
|
|
1621
|
+
setSystemTime();
|
|
1622
|
+
const testData = await setupTestData();
|
|
1623
|
+
admin = testData.users.admin;
|
|
1624
|
+
app = new TerrenoApp({
|
|
1625
|
+
configureApp: () => {},
|
|
1626
|
+
skipListen: true,
|
|
1627
|
+
userModel: UserModel as any,
|
|
1628
|
+
}).build();
|
|
1629
|
+
agent = supertest.agent(app);
|
|
1630
|
+
});
|
|
1631
|
+
|
|
1632
|
+
afterEach(() => {
|
|
1633
|
+
setSystemTime();
|
|
1634
|
+
});
|
|
1635
|
+
|
|
1636
|
+
it("responds with an error when userModel.findById throws during authentication", async () => {
|
|
1637
|
+
const jwtLib = (await import("jsonwebtoken")).default;
|
|
1638
|
+
const token = jwtLib.sign({id: admin._id.toString()}, process.env.TOKEN_SECRET as string, {
|
|
1639
|
+
issuer: process.env.TOKEN_ISSUER,
|
|
1640
|
+
});
|
|
1641
|
+
const findSpy = spyOn(UserModel, "findById").mockImplementation(() => {
|
|
1642
|
+
throw new Error("database unavailable");
|
|
1643
|
+
});
|
|
1644
|
+
try {
|
|
1645
|
+
const res = await agent.get("/auth/me").set("authorization", `Bearer ${token}`);
|
|
1646
|
+
expect(res.status).toBeGreaterThanOrEqual(400);
|
|
1647
|
+
} finally {
|
|
1648
|
+
findSpy.mockRestore();
|
|
1649
|
+
}
|
|
1650
|
+
});
|
|
1651
|
+
|
|
1652
|
+
it("calls next(err) when the local login strategy errors", async () => {
|
|
1653
|
+
type Authenticator = (
|
|
1654
|
+
username: string,
|
|
1655
|
+
password: string,
|
|
1656
|
+
done: (err: Error | null) => void
|
|
1657
|
+
) => void;
|
|
1658
|
+
const authSpy = spyOn(
|
|
1659
|
+
UserModel as unknown as {authenticate: () => Authenticator},
|
|
1660
|
+
"authenticate"
|
|
1661
|
+
).mockReturnValue((_username, _password, done) => {
|
|
1662
|
+
done(new Error("strategy failure"));
|
|
1663
|
+
});
|
|
1664
|
+
try {
|
|
1665
|
+
const errApp = new TerrenoApp({
|
|
1666
|
+
configureApp: () => {},
|
|
1667
|
+
skipListen: true,
|
|
1668
|
+
userModel: UserModel as any,
|
|
1669
|
+
}).build();
|
|
1670
|
+
const errAgent = supertest.agent(errApp);
|
|
1671
|
+
const res = await errAgent
|
|
1672
|
+
.post("/auth/login")
|
|
1673
|
+
.send({email: "notAdmin@example.com", password: "password"});
|
|
1674
|
+
expect(res.status).toBeGreaterThanOrEqual(400);
|
|
1675
|
+
} finally {
|
|
1676
|
+
authSpy.mockRestore();
|
|
1677
|
+
}
|
|
1678
|
+
});
|
|
1679
|
+
});
|
|
1680
|
+
|
|
1681
|
+
describe("cookie based JWT extraction", () => {
|
|
1682
|
+
afterEach(() => {
|
|
1683
|
+
setSystemTime();
|
|
1684
|
+
});
|
|
1685
|
+
|
|
1686
|
+
it("authenticates /auth/me from a jwt cookie", async () => {
|
|
1687
|
+
setSystemTime();
|
|
1688
|
+
const {users} = await setupTestData();
|
|
1689
|
+
const jwtLib = (await import("jsonwebtoken")).default;
|
|
1690
|
+
const token = jwtLib.sign({id: String(users.admin._id)}, process.env.TOKEN_SECRET as string, {
|
|
1691
|
+
issuer: process.env.TOKEN_ISSUER,
|
|
1692
|
+
});
|
|
1693
|
+
const app = getBaseServer();
|
|
1694
|
+
// Stand in for cookie-parser: the extractor prefers req.cookies.jwt over the auth header.
|
|
1695
|
+
app.use((req: express.Request, _res: express.Response, next: express.NextFunction) => {
|
|
1696
|
+
req.cookies = {jwt: token};
|
|
1697
|
+
next();
|
|
1698
|
+
});
|
|
1699
|
+
setupAuth(app, UserModel as unknown as AuthUserModel);
|
|
1700
|
+
addMeRoutes(app, UserModel as unknown as AuthUserModel);
|
|
1701
|
+
|
|
1702
|
+
const res = await supertest.agent(app).get("/auth/me").expect(200);
|
|
1703
|
+
expect(res.body.data.email).toBe("admin@example.com");
|
|
1704
|
+
});
|
|
1705
|
+
});
|
|
1706
|
+
|
|
1707
|
+
describe("auth logging outside of the test environment", () => {
|
|
1708
|
+
const originalNodeEnv = process.env.NODE_ENV;
|
|
1709
|
+
|
|
1710
|
+
afterEach(() => {
|
|
1711
|
+
setSystemTime();
|
|
1712
|
+
process.env.NODE_ENV = originalNodeEnv;
|
|
1713
|
+
});
|
|
1714
|
+
|
|
1715
|
+
it("logs JWT setup and successful logins when NODE_ENV is not test", async () => {
|
|
1716
|
+
setSystemTime();
|
|
1717
|
+
await setupTestData();
|
|
1718
|
+
process.env.NODE_ENV = "development";
|
|
1719
|
+
const debugSpy = spyOn(logger, "debug");
|
|
1720
|
+
const infoSpy = spyOn(logger, "info");
|
|
1721
|
+
try {
|
|
1722
|
+
const app = getBaseServer();
|
|
1723
|
+
setupAuth(app, UserModel as unknown as AuthUserModel);
|
|
1724
|
+
addAuthRoutes(app, UserModel as unknown as AuthUserModel);
|
|
1725
|
+
|
|
1726
|
+
const res = await supertest
|
|
1727
|
+
.agent(app)
|
|
1728
|
+
.post("/auth/login")
|
|
1729
|
+
.send({email: "notAdmin@example.com", password: "password"})
|
|
1730
|
+
.expect(200);
|
|
1731
|
+
expect(res.body.data.token).toBeDefined();
|
|
1732
|
+
expect(
|
|
1733
|
+
debugSpy.mock.calls.some(([message]) =>
|
|
1734
|
+
String(message).includes("Setting up JWT Authentication")
|
|
1735
|
+
)
|
|
1736
|
+
).toBe(true);
|
|
1737
|
+
expect(
|
|
1738
|
+
infoSpy.mock.calls.some(([message]) => String(message).includes("User logged in"))
|
|
1739
|
+
).toBe(true);
|
|
1740
|
+
} finally {
|
|
1741
|
+
debugSpy.mockRestore();
|
|
1742
|
+
infoSpy.mockRestore();
|
|
1743
|
+
}
|
|
1744
|
+
});
|
|
1745
|
+
});
|
|
1746
|
+
|
|
1747
|
+
describe("setupAuth validation", () => {
|
|
1748
|
+
it("throws when the user model has no createStrategy", () => {
|
|
1749
|
+
const app = getBaseServer();
|
|
1750
|
+
const modelWithoutStrategy = {} as unknown as AuthUserModel;
|
|
1751
|
+
|
|
1752
|
+
assert.throws(
|
|
1753
|
+
() => setupAuth(app, modelWithoutStrategy),
|
|
1754
|
+
"setupAuth userModel must have .createStrategy()"
|
|
1755
|
+
);
|
|
1756
|
+
});
|
|
1757
|
+
});
|
|
1758
|
+
|
|
1759
|
+
describe("/me routes with an already populated req.user", () => {
|
|
1760
|
+
const buildApp = (
|
|
1761
|
+
user: {_id?: string; id?: string} | undefined,
|
|
1762
|
+
foundUser: unknown
|
|
1763
|
+
): express.Application => {
|
|
1764
|
+
const app = express();
|
|
1765
|
+
app.use(express.json());
|
|
1766
|
+
app.use((req: express.Request, _res: express.Response, next: express.NextFunction) => {
|
|
1767
|
+
req.user = user as unknown as express.Request["user"];
|
|
1768
|
+
next();
|
|
1769
|
+
});
|
|
1770
|
+
const stubUserModel = {
|
|
1771
|
+
findById: async () => foundUser,
|
|
1772
|
+
} as unknown as AuthUserModel;
|
|
1773
|
+
addMeRoutes(app, stubUserModel);
|
|
1774
|
+
return app;
|
|
1775
|
+
};
|
|
1776
|
+
|
|
1777
|
+
it("returns 401 from GET /auth/me when the request user has no id", async () => {
|
|
1778
|
+
await supertest
|
|
1779
|
+
.agent(buildApp({_id: "abc"}, null))
|
|
1780
|
+
.get("/auth/me")
|
|
1781
|
+
.expect(401);
|
|
1782
|
+
});
|
|
1783
|
+
|
|
1784
|
+
it("returns 401 from PATCH /auth/me when the request user has no id", async () => {
|
|
1785
|
+
await supertest
|
|
1786
|
+
.agent(buildApp({_id: "abc"}, null))
|
|
1787
|
+
.patch("/auth/me")
|
|
1788
|
+
.send({name: "Updated"})
|
|
1789
|
+
.expect(401);
|
|
1790
|
+
});
|
|
1791
|
+
|
|
1792
|
+
it("returns 404 from GET /auth/me when the user record no longer exists", async () => {
|
|
1793
|
+
await supertest
|
|
1794
|
+
.agent(buildApp({id: "abc"}, null))
|
|
1795
|
+
.get("/auth/me")
|
|
1796
|
+
.expect(404);
|
|
1797
|
+
});
|
|
1798
|
+
|
|
1799
|
+
it("returns 404 from PATCH /auth/me when the user record no longer exists", async () => {
|
|
1800
|
+
await supertest
|
|
1801
|
+
.agent(buildApp({id: "abc"}, null))
|
|
1802
|
+
.patch("/auth/me")
|
|
1803
|
+
.send({name: "Updated"})
|
|
1804
|
+
.expect(404);
|
|
1805
|
+
});
|
|
1806
|
+
});
|
package/src/auth.ts
CHANGED
|
@@ -227,6 +227,18 @@ export const setPasswordForUser = async (
|
|
|
227
227
|
});
|
|
228
228
|
};
|
|
229
229
|
|
|
230
|
+
/**
|
|
231
|
+
* Returns the duration when `ms` can parse it, otherwise logs and returns undefined so the caller
|
|
232
|
+
* keeps its default. Signing a token with an unparseable duration throws instead.
|
|
233
|
+
*/
|
|
234
|
+
const validateDuration = (envName: string, value: string): StringValue | undefined => {
|
|
235
|
+
if (ms(value as StringValue) === undefined) {
|
|
236
|
+
logger.error(`${envName} is not a valid duration: "${value}". Using the default instead.`);
|
|
237
|
+
return undefined;
|
|
238
|
+
}
|
|
239
|
+
return value as StringValue;
|
|
240
|
+
};
|
|
241
|
+
|
|
230
242
|
/**
|
|
231
243
|
* Generates both an access token (JWT) and a refresh token for a given user.
|
|
232
244
|
*
|
|
@@ -269,14 +281,9 @@ export const generateTokens = async (
|
|
|
269
281
|
if (authOptions?.generateTokenExpiration) {
|
|
270
282
|
tokenOptions.expiresIn = authOptions.generateTokenExpiration(user);
|
|
271
283
|
} else if (process.env.TOKEN_EXPIRES_IN) {
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
ms(process.env.TOKEN_EXPIRES_IN as StringValue);
|
|
276
|
-
tokenOptions.expiresIn = process.env.TOKEN_EXPIRES_IN as StringValue;
|
|
277
|
-
} catch (error) {
|
|
278
|
-
// This error will result in using the default value above of 15m.
|
|
279
|
-
logger.error(error as string);
|
|
284
|
+
const expiresIn = validateDuration("TOKEN_EXPIRES_IN", process.env.TOKEN_EXPIRES_IN);
|
|
285
|
+
if (expiresIn) {
|
|
286
|
+
tokenOptions.expiresIn = expiresIn;
|
|
280
287
|
}
|
|
281
288
|
}
|
|
282
289
|
if (process.env.TOKEN_ISSUER) {
|
|
@@ -293,14 +300,12 @@ export const generateTokens = async (
|
|
|
293
300
|
if (authOptions?.generateRefreshTokenExpiration) {
|
|
294
301
|
refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(user);
|
|
295
302
|
} else if (process.env.REFRESH_TOKEN_EXPIRES_IN) {
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
// This error will result in using the default value above of 30d.
|
|
303
|
-
logger.error(error as string);
|
|
303
|
+
const expiresIn = validateDuration(
|
|
304
|
+
"REFRESH_TOKEN_EXPIRES_IN",
|
|
305
|
+
process.env.REFRESH_TOKEN_EXPIRES_IN
|
|
306
|
+
);
|
|
307
|
+
if (expiresIn) {
|
|
308
|
+
refreshTokenOptions.expiresIn = expiresIn;
|
|
304
309
|
}
|
|
305
310
|
}
|
|
306
311
|
refreshToken = jwt.sign(payload, refreshTokenSecretOrKey, refreshTokenOptions);
|
|
@@ -311,6 +316,10 @@ export const generateTokens = async (
|
|
|
311
316
|
};
|
|
312
317
|
|
|
313
318
|
export const setupAuth = (app: express.Application, userModel: UserModel): void => {
|
|
319
|
+
if (!userModel.createStrategy) {
|
|
320
|
+
throw new APIError({status: 500, title: "setupAuth userModel must have .createStrategy()"});
|
|
321
|
+
}
|
|
322
|
+
|
|
314
323
|
passport.use(new AnonymousStrategy());
|
|
315
324
|
passport.use(userModel.createStrategy());
|
|
316
325
|
passport.use(
|
|
@@ -331,10 +340,6 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
|
|
|
331
340
|
) as passport.Strategy
|
|
332
341
|
);
|
|
333
342
|
|
|
334
|
-
if (!userModel.createStrategy) {
|
|
335
|
-
throw new APIError({status: 500, title: "setupAuth userModel must have .createStrategy()"});
|
|
336
|
-
}
|
|
337
|
-
|
|
338
343
|
const customTokenExtractor: JwtFromRequestFunction = (req) => {
|
|
339
344
|
let token: string | null = null;
|
|
340
345
|
if (req?.cookies?.jwt) {
|
|
@@ -351,9 +356,6 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
|
|
|
351
356
|
}
|
|
352
357
|
|
|
353
358
|
const secretOrKey = process.env.TOKEN_SECRET;
|
|
354
|
-
if (!secretOrKey) {
|
|
355
|
-
throw new APIError({status: 500, title: "TOKEN_SECRET must be set in env."});
|
|
356
|
-
}
|
|
357
359
|
const jwtOpts: StrategyOptions = {
|
|
358
360
|
issuer: process.env.TOKEN_ISSUER,
|
|
359
361
|
jwtFromRequest: customTokenExtractor,
|