fix: Return 401 for tokens with a malformed user id (#14844)

This commit is contained in:
Tom Moor authored and GitHub committed 2026-12-02 08:15:40 -05:00
1 parent 307b385a98
commit f43e077389
2 files changed
+25 -3

No files matched your search

+7
View File
@@ -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({
+18 -3
View File
@@ -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;
}