From 86980d1a9d6978cffc4282747d7c9906ead55ff7 Mon Sep 17 00:00:00 2001 From: Seva Stefkin Date: Tue, 5 Apr 2022 11:23:25 +0200 Subject: [PATCH] Only allow String and Symbol keys in ActionController::Parameters --- actionpack/CHANGELOG.md | 6 ++++++ .../lib/action_controller/metal/strong_parameters.rb | 12 ++++++++++++ .../controller/parameters/parameters_permit_test.rb | 6 ++++++ 3 files changed, 24 insertions(+) diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md index 1ea4689b8ac..96b19d86f8d 100644 --- a/actionpack/CHANGELOG.md +++ b/actionpack/CHANGELOG.md @@ -1,3 +1,9 @@ +* Allow only String and Symbol keys in `ActionController::Parameters`. + Raise `ActionController::InvalidParameterKey` when initializing Parameters + with keys that aren't strings or symbols. + + *Seva Stefkin* + * Add the ability to use custom logic for storing and retrieving CSRF tokens. By default, the token will be stored in the session. Custom classes can be diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb index cbd6ce445c1..8e0ab4e29f9 100644 --- a/actionpack/lib/action_controller/metal/strong_parameters.rb +++ b/actionpack/lib/action_controller/metal/strong_parameters.rb @@ -64,6 +64,16 @@ module ActionController end end + # Raised when initializing Parameters with keys that aren't strings or symbols. + # + # ActionController::Parameters.new(123 => 456) + # # => ActionController::InvalidParameterKey: all keys must be Strings or Symbols + class InvalidParameterKey < ArgumentError + def initialize # :nodoc: + super("all keys must be Strings or Symbols") + end + end + # == Action Controller \Parameters # # Allows you to choose which attributes should be permitted for mass updating @@ -259,6 +269,8 @@ module ActionController # params.permitted? # => true # Person.new(params) # => # def initialize(parameters = {}, logging_context = {}) + raise InvalidParameterKey unless parameters.keys.all? { |key| key.is_a?(String) || key.is_a?(Symbol) } + @parameters = parameters.with_indifferent_access @logging_context = logging_context @permitted = self.class.permit_all_parameters diff --git a/actionpack/test/controller/parameters/parameters_permit_test.rb b/actionpack/test/controller/parameters/parameters_permit_test.rb index 0d1fee62e44..b7badd03e89 100644 --- a/actionpack/test/controller/parameters/parameters_permit_test.rb +++ b/actionpack/test/controller/parameters/parameters_permit_test.rb @@ -519,4 +519,10 @@ class ParametersPermitTest < ActiveSupport::TestCase assert_equal false, params.permitted? end + + test "only String and Symbol keys are allowed" do + assert_raises(ActionController::InvalidParameterKey) do + ActionController::Parameters.new({ foo: 1 } => :bar) + end + end end