dmfay / massive-js

A data mapper for Node.js and PostgreSQL.
2.49k stars 158 forks source link

Preventing SQL injection #512

Closed kazitanvirahsan closed 6 years ago

kazitanvirahsan commented 7 years ago

We are using massive-js library for document searching using finddoc function.

Can you please tell me how do I prevent the sql injection while passing 'Query options'?

From massive-js link, we can find out https://massive-js.readthedocs.io/en/v2/simple_queries/

"order adds the value to the emitted query as an ORDER BY clause. Massive doesn't do any parsing or processing, so everything has to be exactly as you'd paste it into psql yourself."

and the code snippet from the above link

....products.find({ in_stock: true }, { order: [ {field: "price", direction: "desc"}, {field: "specs->>'height'", direction: "asc", type: "int"} ] }, function (err, products) {...});

My question is How do we escape the value of 'field' and 'direction' from above?

I don't mind doing it explicitly before handing over to massive-js.

dmfay commented 7 years ago

If you're accepting textual input directly into the order option as a string, that's an acknowledged vulnerability (also if you can upgrade definitely do so! If you pass order objects they are escaped and you can use normal JSON syntax). I've put off doing anything about it for a while now because there have been other features I've wanted more immediately and the applications I have using Massive don't allow direct input into order by design. I am open to suggestions and pull requests though!

vitaly-t commented 7 years ago

It would take to replace all the query generation with the code that instead generates a query-formatting template, using either Index Variables or Named Parameters, and then pass all the formatting values in via either as.format method or the query methods directly. The driver will take care of escaping everything correctly and prevent SQL injections.

It would also let you throw away most of the JavaScript-side type casting that's currently in the code.

Example from a library that does exactly that: https://github.com/parse-community/parse-server/blob/master/src/Adapters/Storage/Postgres/PostgresStorageAdapter.js

Although that example is far from optimal ;)

dmfay commented 6 years ago

Nothing to do here.