Skip to content

Instantly share code, notes, and snippets.

@atesgoral
Created November 12, 2020 02:28
Show Gist options
  • Save atesgoral/f04d99b3e116f8242c947f922efa1e7b to your computer and use it in GitHub Desktop.
Save atesgoral/f04d99b3e116f8242c947f922efa1e7b to your computer and use it in GitHub Desktop.
A way to prevent accidental leaking of sensitive data
class Sensitive
@@being_responsible = false
def initialize(value)
@value = value
end
def to_s
@@being_responsible ? @value : '[REDACTED]'
end
def inspect
@@being_responsible ? super : '[REDACTED]'
end
def self.responsibly
@@being_responsible = true
yield
ensure
@@being_responsible = false
end
end
require 'json'
s = Sensitive.new('super secret')
puts s
puts s.to_json
puts s.inspect
Sensitive.responsibly do
puts s
puts s.to_json
puts s.inspect
end
puts s
puts s.to_json
puts s.inspect
@atesgoral
Copy link
Author

atesgoral commented Nov 12, 2020

Sensitive data such as credit card numbers or passwords can accidentally leak into logs (e.g. through diagnostic logging) when a log filtering mechanism is not in place. By wrapping sensitive data in a class that requires a special contract to return the actual data, these accidents can be reduced, if not completely prevented.

@atesgoral
Copy link
Author

Output:

[REDACTED]
"[REDACTED]"
[REDACTED]
super secret
"super secret"
#<Sensitive:0x00007f7f7a069dd8 @value="super secret">
[REDACTED]
"[REDACTED]"
[REDACTED]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment