How to handle "Database query built from user-controlled sources" security issue in findById query?

Hello, everybody. My first post here. Hope you are all doing well.

I’ve been using Mongoose as my ODM, and after running the GitHub CodeScanning feature to look for vulnerabilities in my code, if got this warning: “Database query built from user-controlled sources” in a User.findById(user_id) query.

Relevant techs I’m using in my code:
Mongoose, Typescript, express, express-jwt.

What I’m doing is get the user_id from req.auth.sub (ussing express-jwt) and passing the “sub” property (kinda like the id of the JWT) from the JWT as an argument for the findById query. It seems that the problem is that I’m not parsing or controlling the values on the JWT that comes from the client, and passing that value directly as an argument for the query.

I know that I should use the “$eq” op for the values that I’m not controlling like in a User.find({name: {$eq: name_from_request}}), but I don’t know how to handle this sittuation with the findById method.
I was thinking that a User.findOne({"_id": {"$eq": user_id_from_req}}) could do the job, but it doesn’t sound good to me.

TL;DR: Is there a way to use the findById() query with an argument coming for the Request body (in my case, a value from the JWT) without having a “Database query built from user-controlled sources” security issue?

Thanks a lot in advance. Any comment/criticism is welcomed.

Roberto
findById query with uncontrolled value

1 Like