2

If I start a https://sailsjs.com/ App (Service with an API only, no frontend yet), how can I secure the API against SQL injection or unhandled parameters (e.g. type errors or wrong formats)?

FranzHuber23
  • 3,311
  • 5
  • 24
  • 63

1 Answers1

6

1. Policies

You can write policies to keep some users away from some controller actions. Check them HERE

2. Write controllers that check for required parameters

It is that simple. Just return a 400 or res.badRequest() (check it out HERE ) when a parameter is not in body.

3. Use Waterline to help you.

All methods from HERE have ways to sanitize data. But it is your job to check for value types and other validation (like range). If you need to do a raw querie, then use it like HERE and also check for the DOCS and the "valuesToEscape" arg.

PS: 4. Use a validator service

Setup a service that requires a well known npm library to do checks for you! This is useful because you can make a common chunk of code available across your SailS app.

paulogdm
  • 1,572
  • 14
  • 20
  • 1
    If you use Waterline, you don't have to escape parameters, right? – Suisse Jan 24 '18 at 19:39
  • That's what I wanted to ask for the most. Good to know, that waterline already does prevent SQL injection. So the rest to secure the app is quite clear^^ – FranzHuber23 Jan 25 '18 at 08:29
  • 1
    Exactly, but only if you REALLY need to use raw queries. Usually find, findOne, update, associated with populate is enough for 95% of casesw, and they are secure by default. In a big project I only needed raw queries once... – paulogdm Jan 25 '18 at 10:55
  • @paulogdm: What npm would you recommend for these kinds of validation services? – absqueued Jan 25 '18 at 17:52
  • 2
    @ShekharK.Sharma Validator (https://github.com/chriso/validator.js) should be enough. I use a lot of the "Sanitize" methods there. – paulogdm Jan 25 '18 at 18:12
  • Validator really is easy to use and integrate. – FranzHuber23 Mar 18 '18 at 15:12