I am building a REST API for a service to query a MongoDB database. Initially, I went the standard route of providing "/user/1" to search for user id 1, etc. As I got further into the project, other developers started asking if we can add boolean search capabilities, such as being able to do "and", "not" and "or". Thinking of the amount of work needed to create a DSL for this, I thought about just having the REST API accept a MongoDB query JSON object, like so (pretend this is passed via POST):
/query/{"$or": [{"user": "1", "user", "2"}]}
Now, before I pass that query to MongoDB, I will do the following:
- Validate the JSON object
- Make sure the string is used only in the
query
function, notupdate
,runcommand
, oraggregation
- Verify that there is no
$where
clause in the query, since that allows script execution
Would doing this be enough to prevent injection? Reading the MongoDB FAQ, it appears that passing JSON into the query operation is harmless, since you cannot run any javascript with it (with the exception of $where). Is this a safe approach to take?