Search code examples
javascriptnode.jsexpresssanitizationexpress-validator

How do I know my input is being sanitized by express-validator?


I've implemented express-validator and am trying to sanitize an input field where users are searching a particular query.

The test query I'm using is <script>Malicious code</script. As the request comes in, I use:

req.sanitizeQuery('searchQuery');

When I then check to see if the query has been sanitized, the string hasn't been altered/sanitized in any way.

I could be fundamentally misunderstanding sanitization here, in which case please point it out. If I am, then I can go and fill in my gaps on knowledge, but in the meantime, what "test" query can I throw at my sanitizer to check that it's working?


Solution

  • Looking at the documentation, express-validator is meant to be used as middleware.

    So I would say you want some code that looks a bit like this:

    const { validationResult } = require('express-validator/check');
    const { sanitizeQuery } = require('express-validator/filter');
    
    // Setup the request handler, give it some validation middleware
    // then the main request handler
    app.get('/search', [sanitizeQuery('searchQuery').escape()], function(req, res, next) {
      // Deal with any errors
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.mapped() });
      }
    
      // req.query.searchQuery was sanitised via the middleware, it should now
      // be clean.
      console.log(req.query.searchQuery);
    });
    

    We're using the sanitizeQuery function as middleware which is going to sanitise the value req.query.searchQuery. I'm assuming since it's a sanitisation function, it will not trigger any errors coming from validationResult, instead it will return a clean response for you.

    You should then be able to request your service at your {{host}}/search?searchQuery= <script>Malicious code</script> where {{host}} is your services host such as http://localhost:8080.