DEV Community

Shivashankar
Shivashankar

Posted on

rails 6: Prevents logging sensitive info accidentally

Introduction

In Rails generally we filter out sensitive params getting logged in the logs. But it has an issue. It exposes the filtered params when we inspect the object.

Assume we have a user model and for example sake I am not encrypting the password here

class User < ApplicationRecord
  validates :name, :email, :password, presence: true
end

And we have configured our application to filter out password
config/application.rb

config.filter_parameters += ["password"]

When we create a user object, the password gets filtered in the log/console

User.create(name: 'John', email: 'john@example.com', password: 'password')
#<User id: 1, name: 'John', email: "john@example.com", password: [FILTERED] ....>

The catch is when we use inspect method it displays the password and it does not respect the filter_parameters configuration.

Solution

These issues exist upto Rails 5. Rails 6 fixed this issue and also introduced a flexible option filter_attributes

In rails6 we shall filter out sensitive params via our usual configuration.

  config.filter_parameters += ["password"]

and also using filter_attributes as follows

class User < ApplicationRecord
  self.filter_attributes=[:password]
  validates :name, :email, :password, presence: true
end

The filter_attributes is configured in model, it takes priority and ignore the filter_parameters

For example

class User < ApplicationRecord
  self.filter_attributes=[]
  validates :name, :email, :password, presence: true
end
 User.new(password: 'password')

It now reveals password

#<User id: nil, name: nil, password: 'password', created_at: nil, updated_at: nil>

We shall use filter_attributes to not only prevent logging sensitive data but also from logging very huge data fields like blob and text (in case if it not important) thus we shall reduce the size of log file as well :)

Top comments (0)