How would I go about manually filtering a hash using my application's parameter filter?
I imagine it'd go like this:
Rails.application.filter :password => 'pass1234' # => {:password => '[FILTERED]'}
EDIT (clarification): I'm aware that Rails filters the params
hash when writing to the logs. What I want to do is apply that same filter to a different hash at my prerogative before writing it to the logs with something like Rails.logger.info
. I'm calling a remote HTTP query as a part of my application (since most of the backend operates through a remote API), and I'm logging the URL and parameters passed. I want to have the logs but also ensure that none of the sensitive params show up there.
Parameter filters are used to limit or restrict the input values or data that can be specified for a model tool parameter. For example, a Value List filter can be used so that only values from a list can be specified for the parameter.
Rails has built in log filtering so you don't log passwords and credit cards. Works great for that but when you want to trigger a custom log (like to email) and send your own params or other data along with it, the parameters are obviously not auto-filtered.
After a few minutes of shotgunning it, I figured out this was the way to do it:
filters = Rails.application.config.filter_parameters f = ActionDispatch::Http::ParameterFilter.new filters f.filter :password => 'haha' # => {:password=>"[FILTERED]"}
See the config/application.rb
file, towards the end there is a line:
config.filter_parameters += [:password]
This way the "password" param will not be shown in logs, but you can still access the value normally.
Edit
It seem that have misunderstood your meaning of "filter" originally. As for the clarified issue, I have no idea on how to handle it the truly Rails way.
Here is a brute force approach:
CGI::parse(URI.parse(my_url_address_with_params).query)
to get a hash of param/values (note: values are actually stored as an array; here is the discussion).*filtered*
.Rails.logger.info
(or debug
) directly to log.Here is what you should dig into when relying on Rails magical classes and methods:
In Rails 3 the code that does the trick seems to live in ActionDispatch::Http
(ParameterFilter
in particular, method `filtered_parameters'). The documentation is available at API Dock (or, to be honest, very little documentation). You can examine the sources to get an idea of how this works.
My knowledge of Rails internals is not good enough to suggest anything else. I believe that someone with a better understanding of it might be of more help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With