Keeping a Secret

Rails 4 introduces a new way of signing cookies that differs from the previous method in Rails 3. When you upgrade to Rails 4, you are likely to receive a warning:

DEPRECATION WARNING: You didn't set config.secret_key_base.

As pointed out in the guide for upgrading rails, you can simply run

rake secret

to generate a new secret, and paste that into config.secret_key_base inconfig/initializers/secret_token.rb.

However, do we really want this crucial security key to be hard-coded in our application and pushed to our repository? What if our repository is public, like in the case of an open-source app like the gringotts demo?

Well, my friends, we can simply use an ENV variable to store the secret. In config/initializers/secret_token.rb, put this line:

*YourRailsApp*::Application.config.secret_key_base = ENV["SECRET_KEY_BASE"]

Now, we can check in config/initializers/secret_token.rb without worrying about anyone ever seeing the secret key that our application uses to encrypt cookies. But now we need to make sure that ENV["SECRET_KEY_BASE"] will actually be set, both locally and for Heroku.

Locally, we can use the nifty figaro gem to set ENV variables quickly and easily. Following the instructions on the figaro github page, we add gem "figaro" to our Gemfile, run rake figaro:install, then edit our config/application.yml to add the line:

SECRET_KEY_BASE: (really long string output of rake secret)

For Heroku, we could use figaro’s helper rake task for updating Heroku’s config vars (rake figaro:heroku). However, what if we accidentally check in our config/application.yml file? We’d be sharing the secret key used to encrypt our cookies on our production server. Noooo good!

Preferably, we can generate a separate secret key for Heroku

heroku config:set SECRET_KEY_BASE=$(rake secret)

Just realize that when you change your secret key base, all previous versions of your cookies will no longer be valid.

And that’s that. We are now Rails 4 compliant (no more DEPRECATION warning), and we have the added bonus of keeping our secret a secret.

Additional Resources: