asm-products/buckets — pull request #68 by hulbert (2014-09-22 01:03:40+00:00)
Title: Reduce risk of MongoDB query selector attacks

For Bounty 229: ["Defend our API against query selector attacks"](https://assembly.com/buckets/bounties/229)

This is the result of investigating how this style of attack would affect the existing API. There are three primary places that unsanitized user input is being used, via directly using `request.body`, `request.query`, and `request.params`.

Params are always strings, so this should not be susceptible to this style of attack (though there may be others and some more validity checking would be good IMO, especially in a language with no type checking). Query values should generally be strings **if** express is configured in "simple" mode for its query parsing, which is NOT the default. I've changed this setting in this PR.

Finally, the middleware being used automatically parses both JSON and multipart forms and as such any direct access to `request.body.something` would be vulnerable to these query selector attacks.

I've introduced some middleware that recurses through request.body looking for any objects with keys starting with a $ sign. If there are any, then the middleware returns a 403 Forbidden to the end user. I've written tests to test various types of objects and make sure we catch all these $keys. Additionally, I added a test to verify the 403 behavior when sending a JSON request body with this type of key.

In this PR there are a few changes of findOne(_id: id) to findById(id) for consistency.

This is the most Coffeescript I've written at once so if there are things I could improve on I appreciate the feedback. Some of the code could perhaps be organized differently but I'm not sure what the project conventions are.