I’ve spent some time over the last few weeks upgrading 5 Blocks Out to Rails 2.2.2. One of the things I’ve been pondering how to integrate is the new protect_from_forgery feature which aims to deter cross-site request forgery attacks.
By default, Rails 2.x creates a random forgery protection secret string when generating a new app, and hard-codes the secret into environment.rb. As with database passwords, this isn’t the sort of thing you want in your source code repository, especially if your code will be open source, or exposed in some other way to a lot of people over time. So, what to do?
I found two useful ideas on how to deal with this. Both rely on storying the secret in a file distinct from environment.rb. You store this file on your web server, and not in your source repository. This way, your secret key is as secure as your app server.
Here’s a scrap of code I cooked up to do this: http://pastie.org/369075. It looks for a file named config/session_secret.txt and tries to load the key directly from the text in the file. When running in environments such as production or staging it raises an error if it can’t find the file. When running in dev or test environments it silently falls back to using a hard-coded key. Since I use Capistrano to deploy, I’ve added an after-deploy task that links config/session_secret.txt to a central copy of the file.
This is simple and I think it should work pretty well for me. I hope someone else finds it helpful.
Recent Comments