Reputation: 639
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
Reputation: 12900
You have two options:
additionalProperties
as flag into the input schema, will remove all the keys you did not expect from inputWith 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)
const mongoSanitize = require('express-mongo-sanitize');
fastify.addHook('preHandler', function hook (request, reply, done) {
mongoSanitize.sanitize(request.body);
done(null)
})
Upvotes: 2