diff --git a/server/utils/jwt.test.ts b/server/utils/jwt.test.ts index afc3eb47e8..78e077de5c 100644 --- a/server/utils/jwt.test.ts +++ b/server/utils/jwt.test.ts @@ -104,6 +104,13 @@ describe("getUserForJWT", () => { expect(result.user.id).toEqual(user.id); }); + it("should reject a token with an invalid user id", async () => { + for (const id of [{ foo: "bar" }, "not-a-uuid", undefined]) { + const token = JWT.sign({ id, type: "session" }, "secret"); + await expect(getUserForJWT(token)).rejects.toThrow("Invalid token"); + } + }); + it("should reject a token with a wrong signature for a suspended user", async () => { const admin = await buildAdmin(); const user = await buildUser({ diff --git a/server/utils/jwt.ts b/server/utils/jwt.ts index 1a9d043136..eab47d4bce 100644 --- a/server/utils/jwt.ts +++ b/server/utils/jwt.ts @@ -1,5 +1,6 @@ import { subMinutes } from "date-fns"; import JWT from "jsonwebtoken"; +import isUUID from "validator/lib/isUUID"; import type { FindOptions } from "sequelize"; import { Minute } from "@shared/utils/time"; import { Team, User } from "@server/models"; @@ -61,7 +62,7 @@ export async function getUserForJWT( throw AuthenticationError("Expired token"); } - const user = await User.findByPk(payload.id, { + const user = await User.findByPk(getUserId(payload), { include: [ { model: Team, @@ -151,7 +152,7 @@ export async function getUserForEmailSigninToken( throw AuthenticationError("Token mismatch"); } - const user = await User.scope("withTeam").findByPk(payload.id, { + const user = await User.scope("withTeam").findByPk(getUserId(payload), { rejectOnEmpty: true, }); @@ -203,7 +204,7 @@ export async function getDetailsForEmailUpdateToken( } const email = payload.email; - const user = await User.findByPk(payload.id, { + const user = await User.findByPk(getUserId(payload), { rejectOnEmpty: true, ...options, }); @@ -216,3 +217,17 @@ export async function getDetailsForEmailUpdateToken( return { user, email }; } + +/** + * Reads the user ID from an unverified token payload. + * + * @param payload the decoded token payload. + * @returns the user ID. + * @throws AuthenticationError if the ID is not a UUID. + */ +function getUserId(payload: JWT.JwtPayload): string { + if (typeof payload.id !== "string" || !isUUID(payload.id)) { + throw AuthenticationError("Invalid token"); + } + return payload.id; +}