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.
1. Mark the fields
Section titled “1. Mark the fields”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, :integerend
gardener = Gardener.new(email: 'rows@example.org', password: 'compost9', api_token: 'sprout_key_5521')2. Check what prints
Section titled “2. Check what prints”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') # => trueLoggers call inspect on what they receive, and pp shares the same masking, nested structs and their arrays included.
io = StringIO.newLogger.new(io).info(gardener)io.string.include?('sprout_key_5521') # => falseio.string.include?('[FILTERED]') # => true3. Mind the data paths
Section titled “3. Mind the data paths”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"4. Filter before you log or send a hash
Section titled “4. Filter before you log or send a hash”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.
See also
Section titled “See also”FieldStruct, Actionable and their adapters are open source under the MIT license.