From 55752ac596bcf2a32d75e35b3f6350e8d7d15943 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Mon, 26 Mar 2012 17:29:01 -0700 Subject: [PATCH] added input sanitization --- lib/validation.js | 10 +++++++++- test/validation.test.js | 13 ++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/lib/validation.js b/lib/validation.js index 6a0cc82..48b38d8 100644 --- a/lib/validation.js +++ b/lib/validation.js @@ -15,6 +15,7 @@ module.exports = function (req, res, next) { , resource = req.resource , validation , err + , sanitized = {} ; // rewrite queries from references @@ -37,7 +38,14 @@ module.exports = function (req, res, next) { } // if trying to write data - if((method === 'POST' || method === 'PUT') && resource && resource.properties) { + if((method === 'POST' || method === 'PUT') && req.body && resource && resource.properties) { + // sanitize data + Object.keys(resource.properties).forEach(function (key) { + sanitized[key] = req.body[key]; + }) + + // replace input with sanitized data + req.body = req.data = sanitized; // validate JSON validation = revalidator.validate(req.body, resource); diff --git a/test/validation.test.js b/test/validation.test.js index 3c8ded2..bcbf947 100644 --- a/test/validation.test.js +++ b/test/validation.test.js @@ -12,7 +12,7 @@ describe('Resource Actions', function(){ describe('POST /todos', function(){ it('should return an error when provided invalid data', function(done) { - todos.post({foo: 'bar', bat: 'baz'}, function (err, todo, req, res) { + todos.post({title: 123}, function (err, todo, req, res) { expect(err).to.exist; expect(err.valid).to.equal(false); expect(err.errors).to.have.length(1); @@ -21,6 +21,17 @@ describe('Resource Actions', function(){ }) }) + it('should ignore properties outside the schema', function(done) { + todos.post({title: 'foo', bat: 'baz'}, function (err, todo, req, res) { + todos.get(function (err, todos) { + var todo = todos[0]; + expect(todo.title).to.equal('foo'); + expect(todo.bat).to.not.exist; + done(err); + }) + }) + }) + it('should save the todo when valid', function(done) { todos.post({title: 'feed the cat'}, function (err, todo) { expect(todo._id).to.exist;