Rails:从日志中过滤JSON参数中的敏感数据 [英] Rails: Filter sensitive data in JSON parameter from logs
问题描述
我正在运行Rails 3,并尝试从日志中过滤掉敏感信息,这些日志是作为POST参数传递的JSON Blob.例如,用户创建可能会使用名为user
的发布参数,该发布参数的字符串值是JSON对象. JSON对象中的键之一是password
,我们希望将其从日志中过滤掉.我发现做到这一点的最佳方法是在我们的filter_params中添加一个块,如下所示:
I am running Rails 3 and trying to filter sensitive information out of our logs which are JSON blobs that are passed as post parameters. For example, user creation might take a post param called user
with a string value that is a JSON object. One of the keys in the JSON object is password
and we want to filter this out of our logs. The best way I found to do this was to add a block to our filter_params, like so:
keys_to_filter = ['password', 'password_confirmation']
config.filter_parameters << lambda do |k,v|
if v.is_a? String
keys_to_filter.each do |key|
# Match "key":"<filter_out>", or "key":"<filter_out>"}, allowing for whitespace
v.sub!(/("\s*#{key}\s*")\s*:\s*"[^,\}]*"\s*([,\}])/, "\\1:\"[FILTERED]\"\\2")
end
end
end
这会在filter_params中添加一个块,从而导致错误,该错误在另一个问题中进行了描述:
This adds a block to the filter_params, which causes an error which is described in another question: Rails: ParameterFilter::compiled_filter tries to dup symbol
似乎将块传递给filter_parameters是不安全的,所以我想知道是否还有另一种方法可以解决此问题.
It appears that it is not safe to pass a block to filter_parameters, so I'm wondering if there is another way to solve this problem.
推荐答案
为什么@Nesbitt的答案被否决了(下面)?当然,它引用了测试套件中的代码,但是该测试套件仅测试了ActionDispatch :: Http :: FilterParameters:
Why is @Nesbitt's answer downvoted (down below)? Sure, it references code in a test suite, but that test suite is just testing a feature documented in ActionDispatch::Http::FilterParameters:
如果给出了一个块,则将参数哈希的每个键和值以及所有子哈希传递给它,则可以使用String#replace或类似方法替换该值或键.
If a block is given, each key and value of the params hash and all subhashes is passed to it, the value or key can be replaced using String#replace or similar method.
在Rails 3.x的API文档中查看注释此处.
See comments in the API docs for Rails 3.x here.
我需要做同样的事情:转换通过HTTP POST发送到Rails 3应用程序的JSON blob中的字段.就我而言,我只想包含一个字段的哈希摘要,因此在config/application.rb中:
I needed to do the same thing: transform a field in a JSON blob that was sent with an HTTP POST to a Rails 3 app. In my case I just wanted to include a hashed digest of a field, so in config/application.rb:
config.filter_parameters += [:password, lambda {|key, value|
if key.to_s == 'my_key'
value.replace(calculate_my_hash(value))
end
}]
这篇关于Rails:从日志中过滤JSON参数中的敏感数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!