Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord escape variable in join clause

This query works, but is totally open to SQL injection:

products = Product.find(pids,
  :select => 'products.*, P.code',
  :joins => "left join product_dist_match P on
    (P.pid = products.pid and P.cid = #{cid})",
)

How can I properly escape the cid variable? The conditions parameter allows the format ['foo = ?', bar] for this purpose, but joins does not.

I don't want to use find_by_sql because then I would need to add the joins and conditions which are part of the model's default scope (that would not be DRY).

Edit: My table structure is essentially this:

products: pid (primary key)
product_dist_match: pid, cid, code
customers (not used in the query): cid (primary key)

Note that this is a read-only database which Rails only has limited involvement with. I am not planning to set up models for all the tables; I just want to do a simple query as described above, without exposing myself to SQL injection attacks.

like image 701
Mark Eirich Avatar asked Aug 06 '12 15:08

Mark Eirich


2 Answers

The answer I found is to use the .sanitize method on the model:

products = Product.find(pids,
  :select => 'products.*, P.code',
  :joins => 'left join product_dist_match P on
    (P.pid = products.pid and P.cid = ' + Product.sanitize(cid) + ')',
)

If you find a better solution, please post it!

like image 152
Mark Eirich Avatar answered Nov 14 '22 00:11

Mark Eirich


This seems to be more what you were trying to do.

products = Product.find(pids,
    :select => 'products.*, P.code',
    :joins => sanitize_sql_array [
      'left join product_dist_match P on P.pid = products.pid and P.cid = ?', 
       cid
    ]
like image 21
Conan Morris Avatar answered Nov 14 '22 01:11

Conan Morris