strong_parameters.rb 32.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
require "active_support/core_ext/hash/indifferent_access"
require "active_support/core_ext/hash/transform_values"
require "active_support/core_ext/array/wrap"
require "active_support/core_ext/string/filters"
require "active_support/rescuable"
require "action_dispatch/http/upload"
require "rack/test"
require "stringio"
require "set"
require "yaml"
11

12
module ActionController
13 14 15 16
  # Raised when a required parameter is missing.
  #
  #   params = ActionController::Parameters.new(a: {})
  #   params.fetch(:b)
17
  #   # => ActionController::ParameterMissing: param is missing or the value is empty: b
18
  #   params.require(:a)
19
  #   # => ActionController::ParameterMissing: param is missing or the value is empty: a
20
  class ParameterMissing < KeyError
21
    attr_reader :param # :nodoc:
22

23
    def initialize(param) # :nodoc:
24
      @param = param
25
      super("param is missing or the value is empty: #{param}")
26 27 28
    end
  end

29 30
  # Raised when a supplied parameter is not expected and
  # ActionController::Parameters.action_on_unpermitted_parameters
31
  # is set to <tt>:raise</tt>.
32 33 34
  #
  #   params = ActionController::Parameters.new(a: "123", b: "456")
  #   params.permit(:c)
35
  #   # => ActionController::UnpermittedParameters: found unpermitted parameters: a, b
36 37
  class UnpermittedParameters < IndexError
    attr_reader :params # :nodoc:
38

39
    def initialize(params) # :nodoc:
40
      @params = params
41
      super("found unpermitted parameter#{'s' if params.size > 1 }: #{params.join(", ")}")
42 43 44
    end
  end

45
  # == Action Controller \Parameters
46
  #
T
Tom Kadwill 已提交
47
  # Allows you to choose which attributes should be whitelisted for mass updating
48
  # and thus prevent accidentally exposing that which shouldn't be exposed.
49 50
  # Provides two methods for this purpose: #require and #permit. The former is
  # used to mark parameters as required. The latter is used to set the parameter
51
  # as permitted and limit which attributes should be allowed for mass updating.
52 53 54 55 56 57 58 59 60 61
  #
  #   params = ActionController::Parameters.new({
  #     person: {
  #       name: 'Francesco',
  #       age:  22,
  #       role: 'admin'
  #     }
  #   })
  #
  #   permitted = params.require(:person).permit(:name, :age)
62
  #   permitted            # => <ActionController::Parameters {"name"=>"Francesco", "age"=>22} permitted: true>
63 64
  #   permitted.permitted? # => true
  #
65
  #   Person.first.update!(permitted)
66
  #   # => #<Person id: 1, name: "Francesco", age: 22, role: "user">
67
  #
68 69 70 71 72 73 74 75 76
  # It provides two options that controls the top-level behavior of new instances:
  #
  # * +permit_all_parameters+ - If it's +true+, all the parameters will be
  #   permitted by default. The default is +false+.
  # * +action_on_unpermitted_parameters+ - Allow to control the behavior when parameters
  #   that are not explicitly permitted are found. The values can be <tt>:log</tt> to
  #   write a message on the logger or <tt>:raise</tt> to raise
  #   ActionController::UnpermittedParameters exception. The default value is <tt>:log</tt>
  #   in test and development environments, +false+ otherwise.
77
  #
78 79
  # Examples:
  #
80
  #   params = ActionController::Parameters.new
81
  #   params.permitted? # => false
82 83 84 85 86 87
  #
  #   ActionController::Parameters.permit_all_parameters = true
  #
  #   params = ActionController::Parameters.new
  #   params.permitted? # => true
  #
88 89
  #   params = ActionController::Parameters.new(a: "123", b: "456")
  #   params.permit(:c)
90
  #   # => <ActionController::Parameters {} permitted: true>
91 92 93 94 95 96 97
  #
  #   ActionController::Parameters.action_on_unpermitted_parameters = :raise
  #
  #   params = ActionController::Parameters.new(a: "123", b: "456")
  #   params.permit(:c)
  #   # => ActionController::UnpermittedParameters: found unpermitted keys: a, b
  #
98 99 100 101
  # Please note that these options *are not thread-safe*. In a multi-threaded
  # environment they should only be set once at boot-time and never mutated at
  # runtime.
  #
102 103
  # You can fetch values of <tt>ActionController::Parameters</tt> using either
  # <tt>:key</tt> or <tt>"key"</tt>.
104 105 106 107
  #
  #   params = ActionController::Parameters.new(key: 'value')
  #   params[:key]  # => "value"
  #   params["key"] # => "value"
108
  class Parameters
109
    cattr_accessor :permit_all_parameters, instance_accessor: false
110 111
    self.permit_all_parameters = false

112 113
    cattr_accessor :action_on_unpermitted_parameters, instance_accessor: false

114
    delegate :keys, :key?, :has_key?, :values, :has_value?, :value?, :empty?, :include?,
115
      :as_json, to: :@parameters
116

117 118 119 120
    # By default, never raise an UnpermittedParameters exception if these
    # params are present. The default includes both 'controller' and 'action'
    # because they are added by Rails and should be of no concern. One way
    # to change these is to specify `always_permitted_parameters` in your
R
Rafael Chacón 已提交
121 122 123
    # config. For instance:
    #
    #    config.always_permitted_parameters = %w( controller action format )
124 125 126
    cattr_accessor :always_permitted_parameters
    self.always_permitted_parameters = %w( controller action )

127 128 129 130
    # Returns a new instance of <tt>ActionController::Parameters</tt>.
    # Also, sets the +permitted+ attribute to the default value of
    # <tt>ActionController::Parameters.permit_all_parameters</tt>.
    #
U
Uģis Ozols 已提交
131
    #   class Person < ActiveRecord::Base
132 133 134 135
    #   end
    #
    #   params = ActionController::Parameters.new(name: 'Francesco')
    #   params.permitted?  # => false
136
    #   Person.new(params) # => ActiveModel::ForbiddenAttributesError
137 138 139 140
    #
    #   ActionController::Parameters.permit_all_parameters = true
    #
    #   params = ActionController::Parameters.new(name: 'Francesco')
141
    #   params.permitted?  # => true
142
    #   Person.new(params) # => #<Person id: nil, name: "Francesco">
143 144
    def initialize(parameters = {})
      @parameters = parameters.with_indifferent_access
145
      @permitted = self.class.permit_all_parameters
146 147
    end

148
    # Returns true if another +Parameters+ object contains the same content and
149 150 151 152 153 154 155 156 157 158 159 160 161
    # permitted flag.
    def ==(other)
      if other.respond_to?(:permitted?)
        self.permitted? == other.permitted? && self.parameters == other.parameters
      elsif other.is_a?(Hash)
        ActiveSupport::Deprecation.warn <<-WARNING.squish
          Comparing equality between `ActionController::Parameters` and a
          `Hash` is deprecated and will be removed in Rails 5.1. Please only do
          comparisons between instances of `ActionController::Parameters`. If
          you need to compare to a hash, first convert it using
          `ActionController::Parameters#new`.
        WARNING
        @parameters == other.with_indifferent_access
162
      else
163
        @parameters == other
164 165 166
      end
    end

167 168
    # Returns a safe <tt>ActiveSupport::HashWithIndifferentAccess</tt>
    # representation of this parameter with all unpermitted keys removed.
169 170 171 172 173 174 175 176 177 178 179
    #
    #   params = ActionController::Parameters.new({
    #     name: 'Senjougahara Hitagi',
    #     oddity: 'Heavy stone crab'
    #   })
    #   params.to_h # => {}
    #
    #   safe_params = params.permit(:name)
    #   safe_params.to_h # => {"name"=>"Senjougahara Hitagi"}
    def to_h
      if permitted?
180
        convert_parameters_to_hashes(@parameters, :to_h)
181 182 183 184 185
      else
        slice(*self.class.always_permitted_parameters).permit!.to_h
      end
    end

186 187 188
    # Returns an unsafe, unfiltered
    # <tt>ActiveSupport::HashWithIndifferentAccess</tt> representation of this
    # parameter.
189 190 191 192 193 194
    #
    #   params = ActionController::Parameters.new({
    #     name: 'Senjougahara Hitagi',
    #     oddity: 'Heavy stone crab'
    #   })
    #   params.to_unsafe_h
195
    #   # => {"name"=>"Senjougahara Hitagi", "oddity" => "Heavy stone crab"}
P
Prem Sichanugrist 已提交
196
    def to_unsafe_h
197
      convert_parameters_to_hashes(@parameters, :to_unsafe_h)
P
Prem Sichanugrist 已提交
198 199 200
    end
    alias_method :to_unsafe_hash, :to_unsafe_h

T
Tom Kadwill 已提交
201
    # Convert all hashes in values into parameters, then yield each pair in
202 203
    # the same way as <tt>Hash#each_pair</tt>
    def each_pair(&block)
204 205
      @parameters.each_pair do |key, value|
        yield key, convert_hashes_to_parameters(key, value)
206 207 208 209
      end
    end
    alias_method :each, :each_pair

210 211 212
    # Attribute that keeps track of converted arrays, if any, to avoid double
    # looping in the common use case permit + mass-assignment. Defined in a
    # method to instantiate it only if needed.
213 214 215 216
    #
    # Testing membership still loops, but it's going to be faster than our own
    # loop that converts values. Also, we are not going to build a new array
    # object per fetch.
217
    def converted_arrays
218
      @converted_arrays ||= Set.new
219 220
    end

221 222 223 224 225 226 227 228 229 230
    # Returns +true+ if the parameter is permitted, +false+ otherwise.
    #
    #   params = ActionController::Parameters.new
    #   params.permitted? # => false
    #   params.permit!
    #   params.permitted? # => true
    def permitted?
      @permitted
    end

231 232 233 234 235 236 237
    # Sets the +permitted+ attribute to +true+. This can be used to pass
    # mass assignment. Returns +self+.
    #
    #   class Person < ActiveRecord::Base
    #   end
    #
    #   params = ActionController::Parameters.new(name: 'Francesco')
238
    #   params.permitted?  # => false
239 240 241 242
    #   Person.new(params) # => ActiveModel::ForbiddenAttributesError
    #   params.permit!
    #   params.permitted?  # => true
    #   Person.new(params) # => #<Person id: nil, name: "Francesco">
243
    def permit!
244
      each_pair do |key, value|
C
Corey Ward 已提交
245 246
        Array.wrap(value).each do |v|
          v.permit! if v.respond_to? :permit!
247
        end
248 249
      end

250 251 252 253
      @permitted = true
      self
    end

254 255 256 257
    # This method accepts both a single key and an array of keys.
    #
    # When passed a single key, if it exists and its associated value is
    # either present or the singleton +false+, returns said value:
258
    #
259
    #   ActionController::Parameters.new(person: { name: 'Francesco' }).require(:person)
260
    #   # => <ActionController::Parameters {"name"=>"Francesco"} permitted: false>
261
    #
262 263 264 265 266
    # Otherwise raises <tt>ActionController::ParameterMissing</tt>:
    #
    #   ActionController::Parameters.new.require(:person)
    #   # ActionController::ParameterMissing: param is missing or the value is empty: person
    #
267
    #   ActionController::Parameters.new(person: nil).require(:person)
268 269 270 271
    #   # ActionController::ParameterMissing: param is missing or the value is empty: person
    #
    #   ActionController::Parameters.new(person: "\t").require(:person)
    #   # ActionController::ParameterMissing: param is missing or the value is empty: person
272
    #
273
    #   ActionController::Parameters.new(person: {}).require(:person)
274 275 276
    #   # ActionController::ParameterMissing: param is missing or the value is empty: person
    #
    # When given an array of keys, the method tries to require each one of them
X
Xavier Noria 已提交
277
    # in order. If it succeeds, an array with the respective return values is
278 279 280
    # returned:
    #
    #   params = ActionController::Parameters.new(user: { ... }, profile: { ... })
281
    #   user_params, profile_params = params.require([:user, :profile])
282
    #
T
Tom Kadwill 已提交
283
    # Otherwise, the method re-raises the first exception found:
284
    #
285
    #   params = ActionController::Parameters.new(user: {}, profile: {})
286
    #   user_params, profile_params = params.require([:user, :profile])
287 288 289 290 291 292 293 294 295 296
    #   # ActionController::ParameterMissing: param is missing or the value is empty: user
    #
    # Technically this method can be used to fetch terminal values:
    #
    #   # CAREFUL
    #   params = ActionController::Parameters.new(person: { name: 'Finn' })
    #   name = params.require(:person).require(:name) # CAREFUL
    #
    # but take into account that at some point those ones have to be permitted:
    #
297 298 299
    #   def person_params
    #     params.require(:person).permit(:name).tap do |person_params|
    #       person_params.require(:name) # SAFER
300 301
    #     end
    #   end
302
    #
303
    # for example.
304
    def require(key)
X
Xavier Noria 已提交
305
      return key.map { |k| require(k) } if key.is_a?(Array)
306 307 308 309 310 311
      value = self[key]
      if value.present? || value == false
        value
      else
        raise ParameterMissing.new(key)
      end
312 313
    end

314
    # Alias of #require.
315 316
    alias :required :require

317
    # Returns a new <tt>ActionController::Parameters</tt> instance that
318 319
    # includes only the given +filters+ and sets the +permitted+ attribute
    # for the object to +true+. This is useful for limiting which attributes
320 321 322 323
    # should be allowed for mass updating.
    #
    #   params = ActionController::Parameters.new(user: { name: 'Francesco', age: 22, role: 'admin' })
    #   permitted = params.require(:user).permit(:name, :age)
324
    #   permitted.permitted?      # => true
325 326 327 328
    #   permitted.has_key?(:name) # => true
    #   permitted.has_key?(:age)  # => true
    #   permitted.has_key?(:role) # => false
    #
329 330 331 332
    # Only permitted scalars pass the filter. For example, given
    #
    #   params.permit(:name)
    #
333
    # +:name+ passes if it is a key of +params+ whose associated value is of type
334
    # +String+, +Symbol+, +NilClass+, +Numeric+, +TrueClass+, +FalseClass+,
335 336 337
    # +Date+, +Time+, +DateTime+, +StringIO+, +IO+,
    # +ActionDispatch::Http::UploadedFile+ or +Rack::Test::UploadedFile+.
    # Otherwise, the key +:name+ is filtered out.
338 339 340 341
    #
    # You may declare that the parameter should be an array of permitted scalars
    # by mapping it to an empty array:
    #
342
    #   params = ActionController::Parameters.new(tags: ['rails', 'parameters'])
343
    #   params.permit(tags: [])
344
    #
345 346 347
    # You can also use +permit+ on nested parameters, like:
    #
    #   params = ActionController::Parameters.new({
348
    #     person: {
349 350 351 352 353 354 355 356 357
    #       name: 'Francesco',
    #       age:  22,
    #       pets: [{
    #         name: 'Purplish',
    #         category: 'dogs'
    #       }]
    #     }
    #   })
    #
358
    #   permitted = params.permit(person: [ :name, { pets: :name } ])
359 360
    #   permitted.permitted?                    # => true
    #   permitted[:person][:name]               # => "Francesco"
361
    #   permitted[:person][:age]                # => nil
362 363
    #   permitted[:person][:pets][0][:name]     # => "Purplish"
    #   permitted[:person][:pets][0][:category] # => nil
364 365 366 367 368 369 370 371
    #
    # Note that if you use +permit+ in a key that points to a hash,
    # it won't allow all the hash. You also need to specify which
    # attributes inside the hash should be whitelisted.
    #
    #   params = ActionController::Parameters.new({
    #     person: {
    #       contact: {
I
Ilya Vorontsov 已提交
372
    #         email: 'none@test.com',
373 374 375 376 377 378
    #         phone: '555-1234'
    #       }
    #     }
    #   })
    #
    #   params.require(:person).permit(:contact)
379
    #   # => <ActionController::Parameters {} permitted: true>
380 381
    #
    #   params.require(:person).permit(contact: :phone)
382
    #   # => <ActionController::Parameters {"contact"=><ActionController::Parameters {"phone"=>"555-1234"} permitted: true>} permitted: true>
383 384
    #
    #   params.require(:person).permit(contact: [ :email, :phone ])
385
    #   # => <ActionController::Parameters {"contact"=><ActionController::Parameters {"email"=>"none@test.com", "phone"=>"555-1234"} permitted: true>} permitted: true>
386 387 388
    def permit(*filters)
      params = self.class.new

389
      filters.flatten.each do |filter|
390
        case filter
391 392
        when Symbol, String
          permitted_scalar_filter(params, filter)
393
        when Hash then
394
          hash_filter(params, filter)
395 396 397
        end
      end

398
      unpermitted_parameters!(params) if self.class.action_on_unpermitted_parameters
399

400 401 402
      params.permit!
    end

403 404 405
    # Returns a parameter for the given +key+. If not found,
    # returns +nil+.
    #
406
    #   params = ActionController::Parameters.new(person: { name: 'Francesco' })
407
    #   params[:person] # => <ActionController::Parameters {"name"=>"Francesco"} permitted: false>
408
    #   params[:none]   # => nil
409
    def [](key)
410 411 412
      convert_hashes_to_parameters(key, @parameters[key])
    end

413 414
    # Assigns a value to a given +key+. The given key may still get filtered out
    # when +permit+ is called.
415 416
    def []=(key, value)
      @parameters[key] = value
417 418
    end

419 420 421 422 423 424 425
    # Returns a parameter for the given +key+. If the +key+
    # can't be found, there are several options: With no other arguments,
    # it will raise an <tt>ActionController::ParameterMissing</tt> error;
    # if more arguments are given, then that will be returned; if a block
    # is given, then that will be run and its result returned.
    #
    #   params = ActionController::Parameters.new(person: { name: 'Francesco' })
426
    #   params.fetch(:person)               # => <ActionController::Parameters {"name"=>"Francesco"} permitted: false>
427
    #   params.fetch(:none)                 # => ActionController::ParameterMissing: param is missing or the value is empty: none
428
    #   params.fetch(:none, 'Francesco')    # => "Francesco"
429
    #   params.fetch(:none) { 'Francesco' } # => "Francesco"
A
Akira Matsuda 已提交
430
    def fetch(key, *args)
431
      convert_value_to_parameters(
432 433 434 435 436 437
        @parameters.fetch(key) {
          if block_given?
            yield
          else
            args.fetch(0) { raise ActionController::ParameterMissing.new(key) }
          end
438
        }
439
      )
440 441
    end

442 443 444 445
    if Hash.method_defined?(:dig)
      # Extracts the nested parameter from the given +keys+ by calling +dig+
      # at each step. Returns +nil+ if any intermediate step is +nil+.
      #
446 447 448
      #   params = ActionController::Parameters.new(foo: { bar: { baz: 1 } })
      #   params.dig(:foo, :bar, :baz) # => 1
      #   params.dig(:foo, :zot, :xyz) # => nil
449
      #
450 451
      #   params2 = ActionController::Parameters.new(foo: [10, 11, 12])
      #   params2.dig(:foo, 1) # => 11
452 453 454 455 456
      def dig(*keys)
        convert_value_to_parameters(@parameters.dig(*keys))
      end
    end

457 458 459 460 461
    # Returns a new <tt>ActionController::Parameters</tt> instance that
    # includes only the given +keys+. If the given +keys+
    # don't exist, returns an empty hash.
    #
    #   params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
462 463
    #   params.slice(:a, :b) # => <ActionController::Parameters {"a"=>1, "b"=>2} permitted: false>
    #   params.slice(:d)     # => <ActionController::Parameters {} permitted: false>
464
    def slice(*keys)
465 466 467
      new_instance_with_inherited_permitted_status(@parameters.slice(*keys))
    end

468 469
    # Returns current <tt>ActionController::Parameters</tt> instance which
    # contains only the given +keys+.
470 471 472 473 474
    def slice!(*keys)
      @parameters.slice!(*keys)
      self
    end

475 476 477 478
    # Returns a new <tt>ActionController::Parameters</tt> instance that
    # filters out the given +keys+.
    #
    #   params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
479 480
    #   params.except(:a, :b) # => <ActionController::Parameters {"c"=>3} permitted: false>
    #   params.except(:d)     # => <ActionController::Parameters {"a"=>1, "b"=>2, "c"=>3} permitted: false>
481 482
    def except(*keys)
      new_instance_with_inherited_permitted_status(@parameters.except(*keys))
483 484
    end

485 486 487
    # Removes and returns the key/value pairs matching the given keys.
    #
    #   params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
488 489
    #   params.extract!(:a, :b) # => <ActionController::Parameters {"a"=>1, "b"=>2} permitted: false>
    #   params                  # => <ActionController::Parameters {"c"=>3} permitted: false>
490
    def extract!(*keys)
491
      new_instance_with_inherited_permitted_status(@parameters.extract!(*keys))
492 493 494 495 496 497 498
    end

    # Returns a new <tt>ActionController::Parameters</tt> with the results of
    # running +block+ once for every value. The keys are unchanged.
    #
    #   params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
    #   params.transform_values { |x| x * 2 }
499
    #   # => <ActionController::Parameters {"a"=>2, "b"=>4, "c"=>6} permitted: false>
500 501 502 503 504
    def transform_values(&block)
      if block
        new_instance_with_inherited_permitted_status(
          @parameters.transform_values(&block)
        )
505
      else
506
        @parameters.transform_values
507 508 509
      end
    end

510 511
    # Performs values transformation and returns the altered
    # <tt>ActionController::Parameters</tt> instance.
512 513 514 515 516
    def transform_values!(&block)
      @parameters.transform_values!(&block)
      self
    end

517 518 519
    # Returns a new <tt>ActionController::Parameters</tt> instance with the
    # results of running +block+ once for every key. The values are unchanged.
    def transform_keys(&block)
520 521 522 523
      if block
        new_instance_with_inherited_permitted_status(
          @parameters.transform_keys(&block)
        )
524
      else
525
        @parameters.transform_keys
526 527 528
      end
    end

J
Jon Atack 已提交
529
    # Performs keys transformation and returns the altered
530
    # <tt>ActionController::Parameters</tt> instance.
531 532 533 534 535
    def transform_keys!(&block)
      @parameters.transform_keys!(&block)
      self
    end

536 537 538 539
    # Deletes and returns a key-value pair from +Parameters+ whose key is equal
    # to key. If the key is not found, returns the default value. If the
    # optional code block is given and the key is not found, pass in the key
    # and return the result of block.
A
Akira Matsuda 已提交
540
    def delete(key)
541
      convert_value_to_parameters(@parameters.delete(key))
542 543
    end

544 545
    # Returns a new instance of <tt>ActionController::Parameters</tt> with only
    # items that the block evaluates to true.
546 547
    def select(&block)
      new_instance_with_inherited_permitted_status(@parameters.select(&block))
548 549 550 551
    end

    # Equivalent to Hash#keep_if, but returns nil if no changes were made.
    def select!(&block)
552 553 554 555 556
      @parameters.select!(&block)
      self
    end
    alias_method :keep_if, :select!

557 558
    # Returns a new instance of <tt>ActionController::Parameters</tt> with items
    # that the block evaluates to true removed.
559 560 561 562
    def reject(&block)
      new_instance_with_inherited_permitted_status(@parameters.reject(&block))
    end

563
    # Removes items that the block evaluates to true and returns self.
564 565 566 567 568 569
    def reject!(&block)
      @parameters.reject!(&block)
      self
    end
    alias_method :delete_if, :reject!

570
    # Returns values that were assigned to the given +keys+. Note that all the
571
    # +Hash+ objects will be converted to <tt>ActionController::Parameters</tt>.
572 573
    def values_at(*keys)
      convert_value_to_parameters(@parameters.values_at(*keys))
574 575
    end

576 577
    # Returns a new <tt>ActionController::Parameters</tt> with all keys from
    # +other_hash+ merges into current hash.
578 579 580 581 582 583 584
    def merge(other_hash)
      new_instance_with_inherited_permitted_status(
        @parameters.merge(other_hash)
      )
    end

    # This is required by ActiveModel attribute assignment, so that user can
585 586 587
    # pass +Parameters+ to a mass assignment methods in a model. It should not
    # matter as we are using +HashWithIndifferentAccess+ internally.
    def stringify_keys # :nodoc:
588 589 590
      dup
    end

591
    def inspect
592
      "<#{self.class} #{@parameters} permitted: #{@permitted}>"
593 594
    end

595 596 597 598
    def self.hook_into_yaml_loading # :nodoc:
      # Wire up YAML format compatibility with Rails 4.2 and Psych 2.0.8 and 2.0.9+.
      # Makes the YAML parser call `init_with` when it encounters the keys below
      # instead of trying its own parsing routines.
599 600
      YAML.load_tags["!ruby/hash-with-ivars:ActionController::Parameters"] = name
      YAML.load_tags["!ruby/hash:ActionController::Parameters"] = name
601 602 603
    end
    hook_into_yaml_loading

604
    def init_with(coder) # :nodoc:
605
      case coder.tag
606
      when "!ruby/hash:ActionController::Parameters"
607 608 609
        # YAML 2.0.8's format where hash instance variables weren't stored.
        @parameters = coder.map.with_indifferent_access
        @permitted  = false
610
      when "!ruby/hash-with-ivars:ActionController::Parameters"
611
        # YAML 2.0.9's Hash subclass format where keys and values
612
        # were stored under an elements hash and `permitted` within an ivars hash.
613 614 615
        @parameters = coder.map["elements"].with_indifferent_access
        @permitted  = coder.map["ivars"][:@permitted]
      when "!ruby/object:ActionController::Parameters"
616 617
        # YAML's Object format. Only needed because of the format
        # backwardscompability above, otherwise equivalent to YAML's initialization.
618
        @parameters, @permitted = coder.map["parameters"], coder.map["permitted"]
619 620 621
      end
    end

622 623 624
    def method_missing(method_sym, *args, &block)
      if @parameters.respond_to?(method_sym)
        message = <<-DEPRECATE.squish
625
          Method #{method_sym} is deprecated and will be removed in Rails 5.1,
626 627 628
          as `ActionController::Parameters` no longer inherits from
          hash. Using this deprecated behavior exposes potential security
          problems. If you continue to use this method you may be creating
629
          a security vulnerability in your app that can be exploited. Instead,
630 631
          consider using one of these documented methods which are not
          deprecated: http://api.rubyonrails.org/v#{ActionPack.version}/classes/ActionController/Parameters.html
632 633 634 635 636 637 638 639
        DEPRECATE
        ActiveSupport::Deprecation.warn(message)
        @parameters.public_send(method_sym, *args, &block)
      else
        super
      end
    end

640
    protected
641 642
      attr_reader :parameters

643 644 645 646
      def permitted=(new_permitted)
        @permitted = new_permitted
      end

647
      def fields_for_style?
648
        @parameters.all? { |k, v| k =~ /\A-?\d+\z/ && (v.is_a?(Hash) || v.is_a?(Parameters)) }
649 650
      end

651
    private
652 653 654 655 656 657
      def new_instance_with_inherited_permitted_status(hash)
        self.class.new(hash).tap do |new_instance|
          new_instance.permitted = @permitted
        end
      end

658
      def convert_parameters_to_hashes(value, using)
659 660
        case value
        when Array
661
          value.map { |v| convert_parameters_to_hashes(v, using) }
662 663
        when Hash
          value.transform_values do |v|
664
            convert_parameters_to_hashes(v, using)
665 666
          end.with_indifferent_access
        when Parameters
667
          value.send(using)
668 669 670 671 672
        else
          value
        end
      end

673
      def convert_hashes_to_parameters(key, value)
674
        converted = convert_value_to_parameters(value)
675
        @parameters[key] = converted unless converted.equal?(value)
676 677 678
        converted
      end

679
      def convert_value_to_parameters(value)
680 681 682
        case value
        when Array
          return value if converted_arrays.member?(value)
683 684
          converted = value.map { |_| convert_value_to_parameters(_) }
          converted_arrays << converted
685
          converted
686
        when Hash
687
          self.class.new(value)
688 689
        else
          value
690 691 692 693
        end
      end

      def each_element(object)
A
Aaron Patterson 已提交
694 695 696 697
        case object
        when Array
          object.grep(Parameters).map { |el| yield el }.compact
        when Parameters
698
          if object.fields_for_style?
A
Aaron Patterson 已提交
699 700 701 702 703 704
            hash = object.class.new
            object.each { |k,v| hash[k] = yield v }
            hash
          else
            yield object
          end
705 706
        end
      end
707 708 709 710 711 712

      def unpermitted_parameters!(params)
        unpermitted_keys = unpermitted_keys(params)
        if unpermitted_keys.any?
          case self.class.action_on_unpermitted_parameters
          when :log
713 714
            name = "unpermitted_parameters.action_controller"
            ActiveSupport::Notifications.instrument(name, keys: unpermitted_keys)
715 716 717 718 719 720 721
          when :raise
            raise ActionController::UnpermittedParameters.new(unpermitted_keys)
          end
        end
      end

      def unpermitted_keys(params)
722
        self.keys - params.keys - self.always_permitted_parameters
723
      end
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747

      #
      # --- Filtering ----------------------------------------------------------
      #

      # This is a white list of permitted scalar types that includes the ones
      # supported in XML and JSON requests.
      #
      # This list is in particular used to filter ordinary requests, String goes
      # as first element to quickly short-circuit the common case.
      #
      # If you modify this collection please update the API of +permit+ above.
      PERMITTED_SCALAR_TYPES = [
        String,
        Symbol,
        NilClass,
        Numeric,
        TrueClass,
        FalseClass,
        Date,
        Time,
        # DateTimes are Dates, we document the type but avoid the redundant check.
        StringIO,
        IO,
748
        ActionDispatch::Http::UploadedFile,
749
        Rack::Test::UploadedFile,
750 751 752 753 754 755 756 757 758 759 760
      ]

      def permitted_scalar?(value)
        PERMITTED_SCALAR_TYPES.any? {|type| value.is_a?(type)}
      end

      def permitted_scalar_filter(params, key)
        if has_key?(key) && permitted_scalar?(self[key])
          params[key] = self[key]
        end

761
        keys.grep(/\A#{Regexp.escape(key)}\(\d+[if]?\)\z/) do |k|
762 763
          if permitted_scalar?(self[k])
            params[k] = self[k]
764 765 766 767 768
          end
        end
      end

      def array_of_permitted_scalars?(value)
A
Aaron Patterson 已提交
769
        if value.is_a?(Array) && value.all? {|element| permitted_scalar?(element)}
770
          yield value
771 772 773
        end
      end

774 775 776 777
      def non_scalar?(value)
        value.is_a?(Array) || value.is_a?(Parameters)
      end

778
      EMPTY_ARRAY = []
779 780 781 782 783
      def hash_filter(params, filter)
        filter = filter.with_indifferent_access

        # Slicing filters out non-declared keys.
        slice(*filter.keys).each do |key, value|
784
          next unless value
A
Aaron Patterson 已提交
785
          next unless has_key? key
786

787
          if filter[key] == EMPTY_ARRAY
788
            # Declaration { comment_ids: [] }.
A
Aaron Patterson 已提交
789
            array_of_permitted_scalars?(self[key]) do |val|
790 791
              params[key] = val
            end
792
          elsif non_scalar?(value)
V
Vipul A M 已提交
793
            # Declaration { user: :name } or { user: [:name, :age, { address: ... }] }.
794
            params[key] = each_element(value) do |element|
A
Aaron Patterson 已提交
795
              element.permit(*Array.wrap(filter[key]))
796 797 798 799
            end
          end
        end
      end
800 801 802

      def initialize_copy(source)
        super
803
        @parameters = @parameters.dup
804
      end
805 806
  end

807
  # == Strong \Parameters
808
  #
809
  # It provides an interface for protecting attributes from end-user
810
  # assignment. This makes Action Controller parameters forbidden
811
  # to be used in Active Model mass assignment until they have been
812 813 814 815 816 817 818
  # whitelisted.
  #
  # In addition, parameters can be marked as required and flow through a
  # predefined raise/rescue flow to end up as a 400 Bad Request with no
  # effort.
  #
  #   class PeopleController < ActionController::Base
819
  #     # Using "Person.create(params[:person])" would raise an
820
  #     # ActiveModel::ForbiddenAttributesError exception because it'd
821 822
  #     # be using mass assignment without an explicit permit step.
  #     # This is the recommended form:
823
  #     def create
824
  #       Person.create(person_params)
825 826 827
  #     end
  #
  #     # This will pass with flying colors as long as there's a person key in the
828
  #     # parameters, otherwise it'll raise an ActionController::MissingParameter
829
  #     # exception, which will get caught by ActionController::Base and turned
830
  #     # into a 400 Bad Request reply.
831 832
  #     def update
  #       redirect_to current_account.people.find(params[:id]).tap { |person|
833
  #         person.update!(person_params)
834 835 836 837 838
  #       }
  #     end
  #
  #     private
  #       # Using a private method to encapsulate the permissible parameters is
839
  #       # just a good pattern since you'll be able to reuse the same permit
840 841 842 843 844 845 846
  #       # list between create and update. Also, you can specialize this method
  #       # with per-user checking of permissible attributes.
  #       def person_params
  #         params.require(:person).permit(:name, :age)
  #       end
  #   end
  #
847
  # In order to use <tt>accepts_nested_attributes_for</tt> with Strong \Parameters, you
848 849
  # will need to specify which nested attributes should be whitelisted. You might want
  # to allow +:id+ and +:_destroy+, see ActiveRecord::NestedAttributes for more information.
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
  #
  #   class Person
  #     has_many :pets
  #     accepts_nested_attributes_for :pets
  #   end
  #
  #   class PeopleController < ActionController::Base
  #     def create
  #       Person.create(person_params)
  #     end
  #
  #     ...
  #
  #     private
  #
  #       def person_params
  #         # It's mandatory to specify the nested attributes that should be whitelisted.
  #         # If you use `permit` with just the key that points to the nested attributes hash,
  #         # it will return an empty hash.
869
  #         params.require(:person).permit(:name, :age, pets_attributes: [ :id, :name, :category ])
870 871 872
  #       end
  #   end
  #
873 874
  # See ActionController::Parameters.require and ActionController::Parameters.permit
  # for more information.
875 876 877 878
  module StrongParameters
    extend ActiveSupport::Concern
    include ActiveSupport::Rescuable

879 880
    # Returns a new ActionController::Parameters object that
    # has been instantiated with the <tt>request.parameters</tt>.
881 882 883 884
    def params
      @_params ||= Parameters.new(request.parameters)
    end

885 886 887 888 889
    # Assigns the given +value+ to the +params+ hash. If +value+
    # is a Hash, this will create an ActionController::Parameters
    # object that has been instantiated with the given +value+ hash.
    def params=(value)
      @_params = value.is_a?(Hash) ? Parameters.new(value) : value
890 891 892
    end
  end
end