Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, can the secret_key_base be updated without losing previously signed data?

In Rails 4.x the secret_key_base is used to sign the session cookie and also any other signed cookies created by calling cookies.signed.

I'd like to update/cycle/roll this secret_key_base, but without losing access to all of the previously signed cookies (I don't mind losing the sessions). Is it possible to do this?

Ideally I'd like something like:

  1. Add new secret_key_base.
  2. Use both the old and new secret_key_base's alongside each other over a period of time, so that cookies signed using the older key can be re-signed with the newer key.
  3. Remove the old secret_key_base.

I know there was similar functionality for upgrading from using a secret_token to a secret_key_base. Is there a way to achieve this using Rails?

like image 775
Felix Avatar asked Jan 07 '16 12:01

Felix


1 Answers

You can achieve this by overwriting some of the methods like encrypted and signed in the cookies middleware to first try to read the cookies with your old secret_key_base. if it succeeds then you can upgrade them to new one. Eventually all old cookies will be upgraded to new ones and then you can just remove your custom patches. Take a look at

https://github.com/rails/rails/blob/8350925bec434168f56b4fae22b5298cb4a83c41/actionpack/lib/action_dispatch/middleware/cookies.rb

also checkout how message verifier is working here.

https://github.com/rails/rails/blob/8350925bec434168f56b4fae22b5298cb4a83c41/actionpack/lib/action_dispatch/middleware/cookies.rb#L251

Hope that helps.

like image 161
Rajesh Sharma Avatar answered Nov 06 '22 18:11

Rajesh Sharma