A lot of times, we ask user for sensitive data such as password, credit card number etc. We should not be able to see this information in logs. So, there must be a way in Rails to filter out these parameters from logs.
Rails provides a way of doing this. We can add parameters to Rails.application.config.filter_parameters.
There is one more way of doing this in Rails. We can also use https://api.rubyonrails.org/classes/ActionDispatch/Http/FilterParameters.html.
However there is still a security issue when we call inspect on an ActiveRecord object for logging purposes. In this case, Rails does not consider Rails.application.config.filter_parameters and displays the sensitive information.
Rails 6 fixes this. It considers Rails.application.config.filter_parameters while inspecting an object.
Rails 6 also provides an alternative way to filter columns on ActiveRecord level by adding filter_attributes on ActiveRecord::Base.
Let’s checkout how it works.
Let’s create a user record and call inspect on it.
We can see that
password is filtered as it is added to
by default in
Now let’s add just
We can see here that
User.filter_attributes took priority over
and removed filtering from password and filtered just email.
Now, let’s add both
We can see that now both
password are filtered out.
Here is the relevant pull request.