Ben
Ben

Reputation: 57227

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?

Upvotes: 18

Views: 17857

Answers (2)

efkan
efkan

Reputation: 13217

There is a new tool providing auto control of coming URL and html body data. https://www.npmjs.com/package/content-filter

Also native escape() method might be used for to protect the database.

Run the code snippet below to see the results.

let a = "{$gt:25}"
console.log(a)
console.log(escape(a))

Upvotes: 1

Peter Lyons
Peter Lyons

Reputation: 146054

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);

Upvotes: 29

Related Questions