Top_bar_btn_squeeze
Monday, Mar 05 2007 no comments

Regardless if you are an a beginner or an expert with dozen rails projects under your belt you should really appreciate the posts at Ruby on Rails Security blog. The devil hides in the details that are all to often overlooked. True the recommendations shared are not rails specific, they are applicable to any other web stack.

One interesting recommendation that caught my eye was having a separate user for running migrations. The reason for this is simple: you don't want a malicious user to inject an drop table users or some similar nastiness in your application. Sure you can avoid SQL injection by restrain yourself to proper query construction Rails or use exclusively the intuitive find_by_ methods. If you feel uncomfortable with the assumption that the entire codebase will never have an improper construction, better add one additional security measure: have a custom user just for database migrations, and not allowing the rails production user to drop tables.

Whilst rails does not set up your project with a custom migration user, it is quite simple to tweak support for this into a rails project. Basically you need to add a custom environment just for database migrations. First lets create a user that can do schema edits, lets call it "app_migrator". This is specific to your RDBMS flavor, and will not document here: use the manual.

Next add a migration entry to your database.yml file. Something simple like:


migration:
  adapter: mysql
  database: app_prod
  username: app_migrator
  password: the_secret_password_goes_here

Note that the database is the same as the one you use for production environment, just the authentication info changes.

Rails will try to load config/environments/RAILS_ENV.rb during its initialization process, next step is to add this file. For our purpose an empty file will suffice:


$touch config/environments/migration.rb

Now lets do a quick test to confirm that all works well:


$script/console migration
Loading migration environment.
>> User
=> User

I've started the console in the "migration" environment and behold it worked! Now tweak the capistrano deploy script. You want to perform the migration within the newly created custom environment. Start by overloading the standard migrate task in your conf/deploy.rb:


task :migrate, :roles => [:db] do
  run "cd #{release_path} && rake db:migrate RAILS_ENV=migrate"
end

Commit your changes and enjoy!

Disclaimer: Security comes in layers and not by a single measure. By following the above recipe you will not gain full protection against sql injections.


Technorati tags: ,

Comments


Bits and pieces about Me glued together by Me!

sponsor
time tracking harvest

Harvest - Simple time tracking, powerful reporting.

Suprss
(Subscribe to this page via RSS!)