Skip to content

Commit

Permalink
Allow filtering params based on parent keys
Browse files Browse the repository at this point in the history
Add the possibility to only filter parameters based on
their full path instead of relying on the immediate key.

    config.filter_parameters += ['credit_card.code']

    { 'credit_card' => { 'code' => '[FILTERED]' },
      'source' => { 'code' => '<%= puts 5 %>' } }
  • Loading branch information
gmalette committed Mar 5, 2014
1 parent ccf8f27 commit df7f383
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
22 changes: 15 additions & 7 deletions actionpack/lib/action_dispatch/http/parameter_filter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,31 +30,39 @@ def self.compile(filters)
when Regexp
regexps << item
else
strings << item.to_s
strings << Regexp.escape(item.to_s)
end
end

deep_regexps, regexps = regexps.partition { |r| r.to_s.include?("\\.") }
deep_strings, strings = strings.partition { |s| s.include?("\\.") }

regexps << Regexp.new(strings.join('|'), true) unless strings.empty?
new regexps, blocks
deep_regexps << Regexp.new(deep_strings.join('|'), true) unless deep_strings.empty?

new regexps, deep_regexps, blocks
end

attr_reader :regexps, :blocks
attr_reader :regexps, :deep_regexps, :blocks

def initialize(regexps, blocks)
def initialize(regexps, deep_regexps, blocks)
@regexps = regexps
@deep_regexps = deep_regexps.any? ? deep_regexps : nil
@blocks = blocks
end

def call(original_params)
def call(original_params, parents = [])
filtered_params = {}

original_params.each do |key, value|
if regexps.any? { |r| key =~ r }
value = FILTERED
elsif deep_regexps && (joined = (parents + [key]).join('.')) && deep_regexps.any? { |r| joined =~ r }
value = FILTERED
elsif value.is_a?(Hash)
value = call(value)
value = call(value, (parents + [key]))
elsif value.is_a?(Array)
value = value.map { |v| v.is_a?(Hash) ? call(v) : v }
value = value.map { |v| v.is_a?(Hash) ? call(v, (parents + [key])) : v }
elsif blocks.any?
key = key.dup
value = value.dup if value.duplicable?
Expand Down
1 change: 1 addition & 0 deletions actionpack/test/dispatch/request_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -923,6 +923,7 @@ class RequestParameterFilter < BaseRequestTest
[{'foo'=>'bar', 'baz'=>'foo'},{'foo'=>'[FILTERED]', 'baz'=>'[FILTERED]'},%w'foo baz'],
[{'bar'=>{'foo'=>'bar','bar'=>'foo'}},{'bar'=>{'foo'=>'[FILTERED]','bar'=>'foo'}},%w'fo'],
[{'foo'=>{'foo'=>'bar','bar'=>'foo'}},{'foo'=>'[FILTERED]'},%w'f banana'],
[{'deep'=>{'cc'=>{'code'=>'bar','bar'=>'foo'},'ss'=>{'code'=>'bar'}}},{'deep'=>{'cc'=>{'code'=>'[FILTERED]','bar'=>'foo'},'ss'=>{'code'=>'bar'}}},%w'deep.cc.code'],
[{'baz'=>[{'foo'=>'baz'}, "1"]}, {'baz'=>[{'foo'=>'[FILTERED]'}, "1"]}, [/foo/]]]

test_hashes.each do |before_filter, after_filter, filter_words|
Expand Down

0 comments on commit df7f383

Please sign in to comment.