Skip to content

Commit

Permalink
Prevent duplicate filters for encrypted attributes
Browse files Browse the repository at this point in the history
When an Active Record encrypted attribute is declared, a filter for it
is automatically added to `config.filter_parameters`.  Prior to this
commit, the filter would be re-added every time the model was reloaded:

  ```ruby
  class Post < ActiveRecord::Base
    encrypts :title
  end
  ```

  ```irb
  irb> Rails.application.config.filter_parameters
  # => [:passw, ..., :ssn]

  irb> Post

  irb> Rails.application.config.filter_parameters
  # => [:passw, ..., :ssn, "post.title"]

  irb> reload!
  irb> Post

  irb> Rails.application.config.filter_parameters
  # => [:passw, ..., :ssn, "post.title", "post.title"]
  ```

This commit ensures filters are only added once so that
`config.filter_parameters` does not grow unbounded.
  • Loading branch information
jonathanhefner committed May 9, 2023
1 parent 2b8b45a commit b3cecf0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
8 changes: 4 additions & 4 deletions activerecord/lib/active_record/encryption/configurable.rb
Expand Up @@ -48,11 +48,11 @@ def encrypted_attribute_was_declared(klass, name) # :nodoc:
end
end

def install_auto_filtered_parameters_hook(application) # :nodoc:
def install_auto_filtered_parameters_hook(app) # :nodoc:
ActiveRecord::Encryption.on_encrypted_attribute_declared do |klass, encrypted_attribute_name|
filter_parameter = [("#{klass.model_name.element}" if klass.name), encrypted_attribute_name.to_s].compact.join(".")
unless excluded_from_filter_parameters?(filter_parameter)
application.config.filter_parameters << filter_parameter
filter = [("#{klass.model_name.element}" if klass.name), encrypted_attribute_name.to_s].compact.join(".")
unless excluded_from_filter_parameters?(filter)
app.config.filter_parameters << filter unless app.config.filter_parameters.include?(filter)
klass.filter_attributes += [encrypted_attribute_name]
end
end
Expand Down
21 changes: 21 additions & 0 deletions railties/test/application/initializers/frameworks_test.rb
Expand Up @@ -376,6 +376,27 @@ def self.<(_)
assert_nil ActiveRecord::Scoping::ScopeRegistry.current_scope(Post)
end

test "filters for Active Record encrypted attributes are added to config.filter_parameters only once" do
rails %w(generate model post title:string)
rails %w(db:migrate)

app_file "app/models/post.rb", <<~RUBY
class Post < ActiveRecord::Base
encrypts :title
end
RUBY

require "#{app_path}/config/environment"

assert Post
filter_parameters = Rails.application.config.filter_parameters.dup

reload

assert Post
assert_equal filter_parameters, Rails.application.config.filter_parameters
end

test "ActiveRecord::MessagePack extensions are installed when using ActiveSupport::MessagePack::CacheSerializer" do
rails %w(generate model post title:string)
rails %w(db:migrate)
Expand Down

0 comments on commit b3cecf0

Please sign in to comment.