Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sanitize user input in Mongoose

Except for this fairly uninformative answer and another unpopular answer, I can't seem to find any resources about sanitizing user input using Mongoose.

There's a blog post here about Node/MongoDB injection which seems good at the server level, but there must be something in the middleware level (i.e. Mongoose) that can sanitize input and ensure reasonable safety in the database.

Is there such a beast, or is it even necessary?

like image 933
Ben Avatar asked Feb 25 '15 03:02

Ben


1 Answers

It seems like the mongo-sanitize npm module is the place to start for the raw escaping functionality. Honestly this sounds more appropriate at the connect/express middleware layer because at the mongoose layer, by design, the code does not exert any expectations on the query/update parameters in terms of whether they are written by the application developer (in which case they must not be sanitized or they won't function correctly) or involve user input (which must be sanitized). Thus I'd recommend middleware functions to sanitize the most common places for user input to enter: req.body, req.query, and req.params. So for example you might do something like (sketch):

var json = require("body-parser").json;
var sanitize = require("mongo-sanitize");

function cleanBody(req, res, next) {
  req.body = sanitize(req.body);
  next();
}

function updateUser(req, res) {
  //...
  // safe to build an update query involving req.body here
}
app.put("/api/users", json(), cleanBody, updateUser);
like image 59
Peter Lyons Avatar answered Sep 20 '22 15:09

Peter Lyons