There are cases when we do not want sensitive data like passwords, card details etc in log files.
Rails provides filter_parameters to achive this.
For example, if we have to filter secret_code of user then
we need to set filter_parameters in the application.rb as below:
config.filter_parameters += ["secret_code"]After sending request to server, our request parameters will look like these:
Parameters: {"authenticity_token"=>"ZKeyrytDDqYbjgHm+ZZicqVrKU/KetThIkmHsFQ/91mQ/eGmIJkELhypgVvAbAg1OR+fN5TA8qk0PrOzDOtAKA==", "user"=>{"first_name"=>"First Name", "last_name"=>"Last Name", "email"=>"[email protected]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "secret_code"=>"[FILTERED]"}, "commit"=>"Create User"}Now if we do User.last then:
> User.last
#=> #<User id: 2, first_name: "First Name", last_name: "Last Name", email: "[email protected]", password_digest: "$2a$12$m6bZtRRBSDCzowE9p/z6ceffMyMYQQ7jSxsTlX8/Oba...", secret_code: "12345", created_at: "2019-11-29 09:32:56", updated_at: "2019-11-29 09:32:56"> We can see that the secret_code of user is not filtered and visible.
Rails 6 has moved ParamterFilter from ActionDispatch to ActiveSupport to solve above security problem.
In Rails 6
> User.last
#=> #<User id: 2, first_name: "First Name", last_name: "Last Name", email: "[email protected]", password_digest: "[FILTERED]", secret_code: "[FILTERED]", created_at: "2019-11-29 09:32:56", updated_at: "2019-11-29 09:32:56"> Now we can see that secret_code is filtered.
Instead of defining as filter_parameters, we can also define attributes as filter_attributes.
> User.filter_attributes = [:secret_code, :password]
#=> [:secret_code, :password]
> User.last
#=> #<User id: 2, first_name: "First Name", last_name: "Last Name", email: "[email protected]", password_digest: "[FILTERED]", secret_code: "[FILTERED]", created_at: "2019-11-29 09:32:56", updated_at: "2019-11-29 09:32:56"> If we have filter_attributes or filter_parameters in regex or proc form,
Rails 6 has added
support for that also.
> User.filter_attributes = [/name/, :secret_code, :password]
#=> [/name/, :secret_code, :password]
> User.last
#=> #<User id: 2, first_name: "[FILTERED]", last_name: "[FILTERED]", email: "[email protected]", password_digest: "[FILTERED]", secret_code: "[FILTERED]", created_at: "2019-11-29 09:32:56", updated_at: "2019-11-29 09:32:56"> 