From 528e59ce2065c35498f9b858ad587d030baf6c98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javi=20Mart=C3=ADn?= Date: Thu, 18 Apr 2024 04:07:14 +0200 Subject: [PATCH] Keep rendering pre-Rails7 ActiveStorage images In commit b3f570512, we changed the key generator hash digest class, and we wrote: > Since we haven't seen any Consul Democracy applications using > encrypted messages and these messages become invalid with this change > (...) We didn't realize that ActiveStorage also used the old hash digest class to generated the signed URLs used to access an image. This doesn't affect us when we generate images using `image.variant`, because that generates a new URL on the fly using the new hash digest class. However, URLs referencing the images generated using the old hash digest class, like the ones in the HTML content generated with CKEditor, would result in 404 errors. So we're rotating the signed IDs generated by earlier versions of ActiveStorage. This way both new and old images will be correctly displayed. Note that, unlike cookies, which will keep working once rotated even if we delete the code to rotate them, old ActiveStorage URLs will always need the code rotating them in order to keep working. --- ...=> active_storage_message_and_cookie_rotator.rb} | 13 +++++++++++++ 1 file changed, 13 insertions(+) rename config/initializers/{cookie_rotator.rb => active_storage_message_and_cookie_rotator.rb} (64%) diff --git a/config/initializers/cookie_rotator.rb b/config/initializers/active_storage_message_and_cookie_rotator.rb similarity index 64% rename from config/initializers/cookie_rotator.rb rename to config/initializers/active_storage_message_and_cookie_rotator.rb index b82c9de1d..c6a97ab74 100644 --- a/config/initializers/cookie_rotator.rb +++ b/config/initializers/active_storage_message_and_cookie_rotator.rb @@ -1,3 +1,16 @@ +# This code was copied from: +# https://github.com/hotwired/turbo-rails/blob/v1.4.0/UPGRADING.md#key-digest-changes-in-111 +# Removing this code will make ActiveStorage image URLs generated with Rails 6.1 +# or earlier inaccessible, causing images attached with CKEditor or linked from +# somewhere else not to be rendered. +Rails.application.config.after_initialize do |app| + key_generator = ActiveSupport::KeyGenerator.new( + app.secret_key_base, iterations: 1000, hash_digest_class: OpenSSL::Digest::SHA1 + ) + + app.message_verifier("ActiveStorage").rotate(key_generator.generate_key("ActiveStorage")) +end + # This code was copied from: # https://guides.rubyonrails.org/v7.0/upgrading_ruby_on_rails.html#key-generator-digest-class-changing-to-use-sha256 # TODO: safe to remove after upgrading to Rails 7.1 or releasing a new