Skip to content
This repository was archived by the owner on Aug 17, 2017. It is now read-only.

Don't mutate the original object when using ActionController::Parameters#fetch #184

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions lib/action_controller/parameters.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def initialize(attributes = nil)

def permit!
each_pair do |key, value|
convert_hashes_to_parameters(key, value)
convert_hashes_to_parameters!(key, value)
self[key].permit! if self[key].respond_to? :permit!
end

Expand Down Expand Up @@ -75,7 +75,7 @@ def permit(*filters)
end

def [](key)
convert_hashes_to_parameters(key, super)
convert_hashes_to_parameters!(key, super)
end

def fetch(key, *args)
Expand Down Expand Up @@ -110,7 +110,7 @@ def convert_value(value)

private

def convert_hashes_to_parameters(key, value)
def convert_hashes_to_parameters!(key, value)
if value.is_a?(Parameters) || !value.is_a?(Hash)
value
else
Expand All @@ -119,6 +119,14 @@ def convert_hashes_to_parameters(key, value)
end
end

def convert_hashes_to_parameters(key, value)
if value.is_a?(Parameters) || !value.is_a?(Hash)
value
else
self.class.new(value)
end
end

#
# --- Filtering ----------------------------------------------------------
#
Expand Down
6 changes: 6 additions & 0 deletions test/parameters_taint_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ class ParametersTaintTest < ActiveSupport::TestCase
end
end

test "fetch doesn't mutates the original object" do
value = @params.fetch(:city, { name: 'Barcelona' })
assert_equal value, ActionController::Parameters.new(name: 'Barcelona')
assert @params[:city].nil?
end

test "not permitted is sticky on accessors" do
assert !@params.slice(:person).permitted?
assert !@params[:person][:name].permitted?
Expand Down