Is exposing mongodb query over REST API safe?
mongodb
Solution
As you already note, due to the nature of the JSON parsing means that MongoDB is not open to the same type of "scripting" injection attacks as can possibly be done with an API that allows SQL to pass through it.
For your point 2. The common sense approach is to have only certain operations as endpoints. So such as `query` or with `update` and basically require authentication on the operations performed by the client. So you would not expose potentially dangerous operations to the API.
Also there is general authentication and roles to consider. So you would only allow the API to perform the actions that are allowed by it's presented "role". That protects you some more without necessarily needing to check this in your code, or at least then just trap the error from an "unauthorized" operation.
Finally for 3. as a possible alternative to checking for the presence of the `$where` operator in a provided query ( though the limitations of what you can do get better with each version ), you can actually turn this off on the server using the `--noscipting` option.
So there really are quite a few protective measures you can take that helps you avoid "script injection" attacks, but generally speaking the same sort of dangers do not exist.
Problem
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, not `update`, `runcommand`, or `aggregation` - 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?