From ea4d7e7f4044c84eb78eb260d89958348718fdf6 Mon Sep 17 00:00:00 2001 From: Adrien Dessy Date: Wed, 18 Dec 2024 18:01:42 +0100 Subject: [PATCH] [TAN-3184] Configure cookie rotation for SHA1 to SHA256 migration --- back/config/initializers/cookie_rotator.rb | 25 ++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 back/config/initializers/cookie_rotator.rb diff --git a/back/config/initializers/cookie_rotator.rb b/back/config/initializers/cookie_rotator.rb new file mode 100644 index 000000000000..1630a937bff4 --- /dev/null +++ b/back/config/initializers/cookie_rotator.rb @@ -0,0 +1,25 @@ +# This initializer sets up cookie rotation to ensure a smooth transition from SHA1 to SHA256, +# which is the hash algorithm used by default by the key generator digest class in Rails 7.0. +# For more information, refer to the Rails 7.0 upgrade guide: +# https://guides.rubyonrails.org/upgrading_ruby_on_rails.html#key-generator-digest-class-changing-to-use-sha256 + +Rails.application.config.after_initialize do + Rails.application.config.action_dispatch.cookies_rotations.tap do |cookies| + authenticated_encrypted_cookie_salt = Rails.application.config.action_dispatch.authenticated_encrypted_cookie_salt + signed_cookie_salt = Rails.application.config.action_dispatch.signed_cookie_salt + + secret_key_base = Rails.application.secret_key_base + + key_generator = ActiveSupport::KeyGenerator.new( + secret_key_base, iterations: 1000, hash_digest_class: OpenSSL::Digest::SHA1 + ) + + key_len = ActiveSupport::MessageEncryptor.key_len + + old_encrypted_secret = key_generator.generate_key(authenticated_encrypted_cookie_salt, key_len) + old_signed_secret = key_generator.generate_key(signed_cookie_salt) + + cookies.rotate :encrypted, old_encrypted_secret + cookies.rotate :signed, old_signed_secret + end +end