Pradip
Pradip

Reputation: 639

Fastify equivalent of express-mongo-sanitize

Hello Fastify Experts,

In MongoDB queries I can pass various operators, which may risks the security aspect by having various attack surfaces.

So before sending the payload, I would like to sanitize the query/filters/sort etc. However I don't think I need to sanitize the request payload as such because Mongo will anyway store it as BSON, hence safer.

Now in Express world, we used to have the express-mongo-sanitize sort of plugin.

What open source plugin you propose for Fastify world to achieve the similar functionality?

Thanks, Pradip

Upvotes: 0

Views: 1019

Answers (1)

Manuel Spigolon
Manuel Spigolon

Reputation: 12900

You have two options:

  1. use the schema eviction: adding additionalProperties as flag into the input schema, will remove all the keys you did not expect from input

With this code, you can submit a payload with:

{
    foo: 'hello',
    $where: 'cut'
  }

and the $where key will be removed.

const fastify = require('fastify')({ logger: true })

fastify.post('/', {
  schema: {
    body: {
      type: 'object',
      additionalProperties: false,
      properties: {
        foo: { type: 'string' }
      }
    }
  }
},
async (request, reply) => {
  console.log(request.body)
  return request.body
})

fastify.listen(8080)
  1. The framework you linked has a module feature and you can integrate it with an hook:
const mongoSanitize = require('express-mongo-sanitize');
fastify.addHook('preHandler', function hook (request, reply, done) {
  mongoSanitize.sanitize(request.body);
  done(null)
})

Upvotes: 2

Related Questions