violet_rails icon indicating copy to clipboard operation
violet_rails copied to clipboard

create migration guide for changing secret key base

Open donrestarone opened this issue 2 years ago • 1 comments
trafficstars

we need to change the secret key base for https://ordinarytrip.com

we need to make sure when the key is changed:

  1. existing asset paths don't break
  2. login works
  3. API system is functional

We need to make sure that the secret key base is changed in a zero downtime kind of way

donrestarone avatar Mar 25 '23 19:03 donrestarone

Changing SECRET_KEY_BASE will break following things:

All the users will be logged out since all the signed cookies will get invalid

FIX:

  • Use config.action_dispatch.cookies_rotations to gracefully rotate all the cookies. Old cookies are seamlessly upgraded to the new ones signed with new SECRET_KEY_BASE.

  • Remove the rotator once all the cookies are updated

  • [WIP] Find a optimal duration to remove the rotator

Ref:

https://guides.rubyonrails.org/security.html#rotating-encrypted-and-signed-cookies-configurations

https://github.com/rails/rails/issues/33503

https://github.com/rails/rails/issues/39964

https://github.com/rails/rails/blob/main/guides/source/upgrading_ruby_on_rails.md#key-generator-digest-class-change-requires-a-cookie-rotator

All assets url will be invalid since active storage uses SECRET_KEY_BASE to create asset urls

FIX:

  • rotate the secret key gracefully for ActiveStorage

Ref:

https://github.com/rails/rails/pull/39623

https://github.com/rails/rails/issues/40435

All the encrypted keys we store in database won't be able to be decrypted

FIX

  • Create a rake task that will decrypt the stored secrets with OLD_SECRET_KEY_BASE and encrypt them again with new SECRET_KEY_BASE
  • Run the task after SECRET_KEY_BASE is changed
STEPS TO REPRODUCE
  • Sign in, Add images to pages and add bearer token in web request api_actions

  • Change the value of SECRET_KEY_BASE in .env.development

  • Restart rails server

  • You will be logged out, images won't load, and see ActiveSupport::MessageEncryptor::InvalidMessage on api_actions page

Pralish avatar Apr 21 '23 15:04 Pralish