diff options
author | Tim Rogers <tim@gocardless.com> | 2016-07-07 10:48:13 +0100 |
---|---|---|
committer | Tim Rogers <tim@gocardless.com> | 2016-07-07 10:48:13 +0100 |
commit | ba3dd5ca04e1b70afab964d32f9c0a6f9cace61c (patch) | |
tree | 5ac62d7b0b5509cfc523a461eddd16390753c521 /actionpack | |
parent | 6038a548fd6bf5722f8b4fd19ec2232c887945ce (diff) | |
download | rails-ba3dd5ca04e1b70afab964d32f9c0a6f9cace61c.tar.gz rails-ba3dd5ca04e1b70afab964d32f9c0a6f9cace61c.tar.bz2 rails-ba3dd5ca04e1b70afab964d32f9c0a6f9cace61c.zip |
Changes to a dupped `ActionController::Parameters` mutate the original
When `ActionController::Parameters` is duplicated with `#dup`, it doesn't create a duplicate of the instance variables (e.g. `@parameters`) but rather maintains the reference (see <http://ruby-doc.org/core-2.3.1/Object.html>). Given that the parameters object is often manipulated as if it were a hash (e.g. with `#delete` and similar methods), this leads to unexpected behaviour, like the following:
```
params = ActionController::Parameters.new(foo: "bar")
duplicated_params = params.dup
duplicated_params.delete(:foo)
params == duplicated_params
```
This fixes the bug by defining a private `#initialize_copy` method, used internally by `#dup`, which makes a copy of `@parameters`.
Diffstat (limited to 'actionpack')
-rw-r--r-- | actionpack/lib/action_controller/metal/strong_parameters.rb | 5 | ||||
-rw-r--r-- | actionpack/test/controller/parameters/dup_test.rb | 25 |
2 files changed, 30 insertions, 0 deletions
diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb index b326695ce2..fea04d98e0 100644 --- a/actionpack/lib/action_controller/metal/strong_parameters.rb +++ b/actionpack/lib/action_controller/metal/strong_parameters.rb @@ -783,6 +783,11 @@ module ActionController end end end + + def initialize_copy(source) + super + @parameters = source.instance_variable_get(:@parameters).dup + end end # == Strong \Parameters diff --git a/actionpack/test/controller/parameters/dup_test.rb b/actionpack/test/controller/parameters/dup_test.rb new file mode 100644 index 0000000000..cf273933bd --- /dev/null +++ b/actionpack/test/controller/parameters/dup_test.rb @@ -0,0 +1,25 @@ +require 'abstract_unit' +require 'action_controller/metal/strong_parameters' + +class ParametersDupTest < ActiveSupport::TestCase + setup do + ActionController::Parameters.permit_all_parameters = false + + @params = ActionController::Parameters.new( + person: { + age: '32', + name: { + first: 'David', + last: 'Heinemeier Hansson' + }, + addresses: [{city: 'Chicago', state: 'Illinois'}] + } + ) + end + + test "changes on a duplicate do not affect the original" do + dupped_params = @params.dup + dupped_params.delete(:person) + assert_not_equal @params, dupped_params + end +end |