1

I have the following ruby On Rails code:

#The user can only ask for a subset of the following columns:
authorized_fields= ["id","created_at","updated_at"]

#The user sends the requested columns as a comma separated string in the fields param
fields = (params[:fields].split(',') & authorized_fields).join(",");

#Build the query to be run:
sql = "SELECT json_agg(u) FROM (SELECT #{fields} FROM table_name) u"

#Run the query against the database
ModelName.connection.select_value(sql)

My question is, is this query SQL Injection safe? My understanding is that since I limit the available fields, so it protects me from injections.

Am I correct? Can someone give me an example of a fields parameter sent by the user which will not be safe?

0

1 Answer 1

1

You may use ActiveRecord::Base.connection.quote_column_name. Code should be like this:

input_fields = params[:fields].split(',').collect do |field| 
  ActiveRecord::Base.connection.quote_column_name(field) 
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.