rails: "on_rotation" callback is not called for ActiveRecord Signed Id

on_rotation is supported by MessageVerifier, but the Signed Id implementation does not pass it through. This feature is very useful for secret-key rotation and monitoring the usage of old keys.

Steps to reproduce

# frozen_string_literal: true

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  gem "rails"
  gem "sqlite3"
end

require "active_record/railtie"
require "minitest/autorun"

ENV["DATABASE_URL"] = "sqlite3::memory:"

class TestApp < Rails::Application
  config.load_defaults Rails::VERSION::STRING.to_f
  config.eager_load = false
  config.logger = Logger.new($stdout)
  config.secret_key_base = "secret_key_base"

  ActiveRecord::Base.signed_id_verifier_secret = "new_secret"
end
Rails.application.initialize!

ActiveRecord::Schema.define do
  create_table :posts, force: true do |t|
  end
end

class Post < ActiveRecord::Base
end

class BugTest < ActiveSupport::TestCase
  def test_association_stuff
    Post.create! id: 1

    on_rotation_is_called = false

    # signed Id of "1" with "old_secret"
    signed_id_with_old_secret = "eyJfcmFpbHMiOnsiZGF0YSI6MSwicHVyIjoicG9zdCJ9fQ--e3c0118ae573077a32264dc32acc63800352323c41039b0e096af64bd6ecc28b"

    Post.signed_id_verifier.rotate "old_secret", on_rotation: -> { on_rotation_is_called = true }
    assert Post.find_signed!(signed_id_with_old_secret, on_rotation: -> { on_rotation_is_called = true })

    assert on_rotation_is_called
  end
end

Expected Behavior

on_rotation should be called, and on_rotation_is_called should become true.

Actual Behavior

The on_rotation method from rotate or find_signed! is not called, leaving on_rotation_is_called as false.

Suggestions

  1. Call on_rotation when it is set using the rotate method. This would require updating the read_message method in activesupport/lib/active_support/messages/rotator.rb file.

  2. Call on_rotation when it is set using find_signed/find_signed!. These methods would need to accept on_rotation as an optional argument.

  3. Implement both solutions.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 15 (15 by maintainers)

Commits related to this issue

Most upvoted comments

Did I understand it correctly?

Yes, I see how it could be a footgun, but that’s how it already worked.

IMO 1 is a bug, as it seems it was intented to work but doesn’t. So should be backport.

2 look more like a new feature and shouldn’t be backported.

I got a fix for 1, just need to add some tests.