-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathauth.ts
More file actions
544 lines (489 loc) · 15.6 KB
/
Copy pathauth.ts
File metadata and controls
544 lines (489 loc) · 15.6 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
import { parseJWT } from "@thirdweb-dev/auth";
import {
ThirdwebAuth,
getToken as getJWT,
type ThirdwebAuthUser,
} from "@thirdweb-dev/auth/fastify";
import { AsyncWallet } from "@thirdweb-dev/wallets/evm/wallets/async";
import type { FastifyInstance } from "fastify";
import type { FastifyRequest } from "fastify/types/request";
import jsonwebtoken, { type JwtPayload } from "jsonwebtoken";
import { createHash } from "node:crypto";
import { validate as uuidValidate } from "uuid";
import { getPermissions } from "../../shared/db/permissions/get-permissions";
import { createToken } from "../../shared/db/tokens/create-token";
import { revokeToken } from "../../shared/db/tokens/revoke-token";
import { WebhooksEventTypes } from "../../shared/schemas/webhooks";
import { THIRDWEB_DASHBOARD_ISSUER, handleSiwe } from "../../shared/utils/auth";
import { getAccessToken } from "../../shared/utils/cache/access-token";
import { getAuthWallet } from "../../shared/utils/cache/auth-wallet";
import { getConfig } from "../../shared/utils/cache/get-config";
import { getWebhooksByEventType } from "../../shared/utils/cache/get-webhook";
import { getKeypair } from "../../shared/utils/cache/keypair";
import { env } from "../../shared/utils/env";
import { logger } from "../../shared/utils/logger";
import { sendWebhookRequest } from "../../shared/utils/webhook";
import { Permission } from "../../shared/schemas/auth";
import { ADMIN_QUEUES_BASEPATH } from "./admin-routes";
import { OPENAPI_ROUTES } from "./open-api";
export type TAuthData = never;
export type TAuthSession = { permissions: string };
interface AuthResponse {
isAuthed: boolean;
user?: ThirdwebAuthUser<TAuthData, TAuthSession>;
// If error is provided, return an error immediately.
error?: string;
}
declare module "fastify" {
interface FastifyRequest {
user: ThirdwebAuthUser<TAuthData, TAuthSession>;
}
}
export async function withAuth(server: FastifyInstance) {
const config = await getConfig();
// Configure the ThirdwebAuth fastify plugin
const { authRouter, authMiddleware, getUser } = ThirdwebAuth<
TAuthData,
TAuthSession
>({
// TODO: Domain needs to be pulled from config as well
domain: config.authDomain,
// We use an async wallet here to load wallet from config every time
wallet: new AsyncWallet({
getSigner: async () => {
const authWallet = await getAuthWallet();
return authWallet.getSigner();
},
cacheSigner: false,
}),
callbacks: {
onLogin: async (walletAddress) => {
// When a user logs in, we check for their permissions in the database
const res = await getPermissions({ walletAddress });
// And we add their permissions as a scope to their JWT
return {
// TODO: Replace with default permissions
permissions: res?.permissions || "none",
};
},
onToken: async (jwt) => {
// When a new JWT is generated, we save it in the database
await createToken({ jwt, isAccessToken: false });
},
onLogout: async (_, req) => {
const jwt = getJWT(req);
if (!jwt) {
return;
}
const { payload } = parseJWT(jwt);
try {
await revokeToken({ id: payload.jti });
} catch {
logger({
service: "server",
level: "error",
message: `[Auth] Failed to revoke token ${payload.jti}`,
});
}
},
},
});
// Setup the auth router and auth middleware
await server.register(authRouter, { prefix: "/auth" });
await server.register(authMiddleware);
// Decorate the request with a null user
server.decorateRequest("user", null);
// Add auth validation middleware to check for authenticated requests
// Note: in the onRequest hook, request.body will always be undefined, because the body parsing happens before the preValidation hook.
// https://fastify.dev/docs/latest/Reference/Hooks/#onrequest
server.addHook("preValidation", async (req, res) => {
// Skip auth check in sandbox mode
if (env.ENGINE_MODE === "sandbox") {
return;
}
let message =
"Please provide a valid access token or other authentication. See: https://portal.thirdweb.com/engine/features/access-tokens";
try {
const { isAuthed, user, error } = await onRequest({ req, getUser });
if (isAuthed) {
if (user) {
req.user = user;
}
// Allow this request to proceed.
return;
}
if (error) {
message = error;
}
} catch (err: unknown) {
logger({
service: "server",
level: "warn",
message: "Error authenticating user",
error: err,
});
}
return res.status(401).send({
error: "Unauthorized",
message,
});
});
}
export const onRequest = async ({
req,
getUser,
}: {
req: FastifyRequest;
getUser: ReturnType<typeof ThirdwebAuth<TAuthData, TAuthSession>>["getUser"];
}): Promise<AuthResponse> => {
// Handle websocket auth separately.
if (req.headers.upgrade?.toLowerCase() === "websocket") {
return handleWebsocketAuth(req, getUser);
}
const publicRoutesResp = handlePublicEndpoints(req);
if (publicRoutesResp.isAuthed) {
return publicRoutesResp;
}
const jwt = getJWT(req);
if (jwt) {
const decoded = jsonwebtoken.decode(jwt, { complete: true });
if (decoded) {
const payload = decoded.payload as JwtPayload;
const header = decoded.header;
// Get the public key from the `iss` payload field.
const publicKey = payload.iss;
if (publicKey) {
const authWallet = await getAuthWallet();
if (publicKey === (await authWallet.getAddress())) {
return await handleAccessToken(jwt, req, getUser);
}
if (publicKey === THIRDWEB_DASHBOARD_ISSUER) {
return await handleDashboardAuth(jwt);
}
return await handleKeypairAuth({ jwt, req, publicKey });
}
// Get the public key hash from the `kid` header.
const publicKeyHash = header.kid;
if (publicKeyHash) {
return await handleKeypairAuth({ jwt, req, publicKeyHash });
}
}
}
const secretKeyResp = await handleSecretKey(req);
if (secretKeyResp.isAuthed) {
return secretKeyResp;
}
const authWebhooksResp = await handleAuthWebhooks(req);
if (authWebhooksResp.isAuthed) {
return authWebhooksResp;
}
// Unauthorized: no auth patterns matched.
return { isAuthed: false };
};
/**
* Handles unauthed routes.
* @param req FastifyRequest
* @returns AuthResponse
*/
const handlePublicEndpoints = (req: FastifyRequest): AuthResponse => {
if (req.method === "GET") {
if (
req.url === "/favicon.ico" ||
req.url === "/" ||
req.url === "/system/health" ||
OPENAPI_ROUTES.includes(req.url) ||
req.url.startsWith("/auth/user") ||
req.url.startsWith("/transaction/status")
) {
return { isAuthed: true };
}
} else if (req.method === "POST") {
if (
req.url.startsWith("/auth/payload") ||
req.url.startsWith("/auth/login") ||
req.url.startsWith("/auth/switch-account") ||
req.url.startsWith("/auth/logout")
) {
return { isAuthed: true };
}
if (req.url.startsWith("/relayer/")) {
const relayerId = req.url.slice("/relayer/".length);
if (uuidValidate(relayerId)) {
// "Relay transaction" endpoint which handles its own authentication.
return { isAuthed: true };
}
}
}
// Admin routes enforce their own auth.
if (req.url.startsWith(ADMIN_QUEUES_BASEPATH)) {
return { isAuthed: true };
}
return { isAuthed: false };
};
/**
* Handle websocket request: auth via access token
* Allow a request that provides a non-revoked access token for an owner/admin
* Handle websocket auth separately.
* @param req FastifyRequest
* @param getUser
* @returns AuthResponse
* @async
*/
const handleWebsocketAuth = async (
req: FastifyRequest,
getUser: ReturnType<typeof ThirdwebAuth<TAuthData, TAuthSession>>["getUser"],
): Promise<AuthResponse> => {
const { token: jwt } = req.query as { token: string };
const token = await getAccessToken({ jwt });
if (token && token.revokedAt === null) {
// Set as a header for `getUsers` to parse the token.
req.headers.authorization = `Bearer ${jwt}`;
const user = await getUser(req);
const { isAllowed, ip } = await checkIpInAllowlist(req);
if (!isAllowed) {
logger({
service: "server",
level: "error",
message: `Unauthorized IP address: ${ip}`,
});
return {
isAuthed: false,
error:
"Unauthorized IP address. See: https://portal.thirdweb.com/engine/features/security",
};
}
if (
user?.session?.permissions === Permission.Owner ||
user?.session?.permissions === Permission.Admin
) {
return { isAuthed: true, user };
}
}
// Destroy the websocket connection.
req.raw.socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
req.raw.socket.destroy();
return { isAuthed: false };
};
/**
* Auth via keypair.
* Allow a request that provides a JWT signed by an ES256 private key
* matching the configured public key.
* @param jwt string
* @param req FastifyRequest
* @param publicKey string
* @returns AuthResponse
*/
const handleKeypairAuth = async (args: {
jwt: string;
req: FastifyRequest;
publicKey?: string;
publicKeyHash?: string;
}): Promise<AuthResponse> => {
// The keypair auth feature must be explicitly enabled.
if (!env.ENABLE_KEYPAIR_AUTH) {
return { isAuthed: false };
}
const { jwt, req, publicKey, publicKeyHash } = args;
let error: string | undefined;
try {
const keypair = await getKeypair({ publicKey, publicKeyHash });
if (!keypair) {
error = "The provided public key is incorrect or not added to Engine.";
throw error;
}
// The JWT is valid if `verify` did not throw.
const payload = jsonwebtoken.verify(jwt, keypair.publicKey, {
algorithms: [keypair.algorithm as jsonwebtoken.Algorithm],
}) as jsonwebtoken.JwtPayload;
// If `bodyHash` is provided, it must match a hash of the POST request body.
if (req.method === "POST" && payload?.bodyHash) {
const computedBodyHash = hashRequestBody(req);
if (computedBodyHash !== payload.bodyHash) {
error = `The request body does not match the hash in the access token. See: https://portal.thirdweb.com/engine/v2/features/keypair-authentication. [hash in access token: ${payload.bodyHash}, hash computed from request: ${computedBodyHash}]`;
throw error;
}
}
const { isAllowed, ip } = await checkIpInAllowlist(req);
if (!isAllowed) {
logger({
service: "server",
level: "error",
message: `Unauthorized IP address: ${ip}`,
});
throw new Error(
"Unauthorized IP address. See: https://portal.thirdweb.com/engine/features/security",
);
}
return { isAuthed: true };
} catch (e) {
if (e instanceof jsonwebtoken.TokenExpiredError) {
error = "Keypair token is expired.";
} else if (!error) {
// Default error.
error =
'Error parsing "Authorization" header. See: https://portal.thirdweb.com/engine/features/access-tokens';
}
}
return { isAuthed: false, error };
};
/**
* Auth via access token.
* Allow a request that provides a non-revoked access token for an owner/admin.
* @param jwt string
* @param req FastifyRequest
* @param getUser
* @returns AuthResponse
* @async
*/
const handleAccessToken = async (
jwt: string,
req: FastifyRequest,
getUser: ReturnType<typeof ThirdwebAuth<TAuthData, TAuthSession>>["getUser"],
): Promise<AuthResponse> => {
let token: Awaited<ReturnType<typeof getAccessToken>> = null;
try {
token = await getAccessToken({ jwt });
} catch (_e) {
// Missing or invalid signature. This will occur if the JWT not intended for this auth pattern.
return { isAuthed: false };
}
if (!token || token.revokedAt) {
return { isAuthed: false };
}
const user = await getUser(req);
if (
user?.session?.permissions !== Permission.Owner &&
user?.session?.permissions !== Permission.Admin
) {
return { isAuthed: false };
}
const { isAllowed, ip } = await checkIpInAllowlist(req);
if (!isAllowed) {
logger({
service: "server",
level: "error",
message: `Unauthorized IP address: ${ip}`,
});
return {
isAuthed: false,
error:
"Unauthorized IP address. See: https://portal.thirdweb.com/engine/features/security",
};
}
return { isAuthed: true, user };
};
/**
* Auth via dashboard.
* Allow a request that provides a dashboard JWT.
* @param jwt string
* @returns AuthResponse
* @async
*/
const handleDashboardAuth = async (jwt: string): Promise<AuthResponse> => {
const user =
(await handleSiwe(jwt, "thirdweb.com", THIRDWEB_DASHBOARD_ISSUER)) ||
(await handleSiwe(jwt, "thirdweb-preview.com", THIRDWEB_DASHBOARD_ISSUER));
if (user) {
const res = await getPermissions({ walletAddress: user.address });
if (
res?.permissions === Permission.Owner ||
res?.permissions === Permission.Admin
) {
return {
isAuthed: true,
user: {
address: user.address,
session: {
permissions: res.permissions,
},
},
};
}
}
return { isAuthed: false };
};
/**
* Auth via thirdweb secret key.
* Allow a request that provides the thirdweb secret key used to init Engine.
*
* @param req FastifyRequest
* @returns
*/
const handleSecretKey = async (req: FastifyRequest): Promise<AuthResponse> => {
const thirdwebApiSecretKey = req.headers.authorization?.split(" ")[1];
if (thirdwebApiSecretKey === env.THIRDWEB_API_SECRET_KEY) {
const authWallet = await getAuthWallet();
return {
isAuthed: true,
user: {
address: await authWallet.getAddress(),
session: {
permissions: Permission.Admin,
},
},
};
}
return { isAuthed: false };
};
/**
* Auth via auth webhooks
* Allow a request if it satisfies all configured auth webhooks.
* Must have at least one auth webhook.
* @param req FastifyRequest
* @returns AuthResponse
* @async
*/
const handleAuthWebhooks = async (
req: FastifyRequest,
): Promise<AuthResponse> => {
const authWebhooks = await getWebhooksByEventType(WebhooksEventTypes.AUTH);
if (authWebhooks.length > 0) {
const authResponses = await Promise.all(
authWebhooks.map(async (webhook) => {
const { ok } = await sendWebhookRequest(webhook, {
url: req.url,
method: req.method,
headers: req.headers,
params: req.params,
query: req.query,
cookies: req.cookies,
body: req.body,
});
return ok;
}),
);
if (authResponses.every((ok) => !!ok)) {
return { isAuthed: true };
}
}
return { isAuthed: false };
};
const hashRequestBody = (req: FastifyRequest): string => {
return createHash("sha256")
.update(JSON.stringify(req.body), "utf8")
.digest("hex");
};
/**
* Check if the request IP is in the allowlist.
* Fetches cached config if available.
* @param req FastifyRequest
* @returns boolean
* @async
*/
const checkIpInAllowlist = async (
req: FastifyRequest,
): Promise<{ isAllowed: boolean; ip: string }> => {
let ip = req.ip;
const trustProxy = env.TRUST_PROXY || !!env.ENGINE_TIER;
if (trustProxy && req.headers["cf-connecting-ip"]) {
ip = req.headers["cf-connecting-ip"] as string;
}
const config = await getConfig();
if (config.ipAllowlist.length === 0) {
return { isAllowed: true, ip };
}
return {
isAllowed: config.ipAllowlist.includes(ip),
ip,
};
};