Skip to content

How to keep sensitive values out of logs

A Gardener record carries a password and an API token, and sooner or later someone will inspect it, pp it or pass it to a logger.

sensitive: true is accepted on every type.

require 'logger'
require 'stringio'
class Gardener < FieldStruct::Base
required :email, :email
optional :password, :string, sensitive: true
optional :api_token, :string, sensitive: true
optional :allotments, :integer
end
gardener = Gardener.new(email: 'rows@example.org', password: 'compost9', api_token: 'sprout_key_5521')

inspect prints [FILTERED] for a value that is set and nil for one that isn’t, so an unset secret still looks different from a set one.

gardener.inspect # => '#<Gardener email: "rows@example.org", password: [FILTERED], api_token: [FILTERED], allotments: nil>'
Gardener.new(email: 'rows@example.org').inspect.include?('password: nil') # => true

Loggers call inspect on what they receive, and pp shares the same masking, nested structs and their arrays included.

io = StringIO.new
Logger.new(io).info(gardener)
io.string.include?('sprout_key_5521') # => false
io.string.include?('[FILTERED]') # => true

The mask is for display only. Readers, attributes, to_h, as_json and to_json return the real value, since code that serializes an object has to have it.

gardener.password # => "compost9"
gardener.to_h[:api_token] # => "sprout_key_5521"

The field metadata knows which fields are sensitive. Filter with it instead of keeping a list by hand.

safe = gardener.to_h.reject { |name, _| Gardener.metadata[name].sensitive? }
safe.keys # => [:email, :allotments]

Error messages never contain the value, only its class, so the errors: part of inspect is safe as well.

FieldStruct, Actionable and their adapters are open source under the MIT license.